FTP下载
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
*/
public class SftpUtils {
/** 日志对象 */
private static Logger log = Logger.getLogger(SftpUtils.class);
/** SFTP服务器主机地址(IP地址) */
private String host;
/** SFTP连接端口 */
private int port;
/** SFTP登录用户名 */
private String username;
/** SFTP登录密码 */
private String password;
/** SFTP连接会话 */
private Session session;
/**
* 无参构造方法
*/
public SftpUtils() {
}
/**
* 构造方法
*
* @param host
* SFTP服务器主机地址(IP地址)
* @param port
* SFTP连接端口
* @param username
* SFTP登录用户名
* @param password
* SFTP登录密码
* @throws JSchException
*/
public SftpUtils(String host, int port, String username, String password)
throws JSchException {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
// 获得SFTP服务器连接
this.createSession();
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* 获得SFTP服务器连接
*
* @throws JSchException
* JSCH异常
*/
public void createSession() throws JSchException {
// 创建JSch对象
JSch jsch = new JSch();
// 根据登录用户名、SFTP服务器主机地址(IP地址)、SFTP连接端口获取一个Session对象
session = jsch.getSession(username, host, port);
// 设置登录密码
session.setPassword(password);
// 设置不验证 HostKey
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// 设置超时5分钟
session.setTimeout(5 * 60 * 1000);
try {
// 打开会话连接
session.connect();
} catch (JSchException jse) {
// 如果连接已打开,需要销毁连接
if (session.isConnected()) {
session.disconnect();
}
throw new JSchException(
"Connect to the server failed.Please check HOST["
+ host
+ "],PORT["
+ port
+ "],USERNAME["
+ username
+ "],PASSWORD["
+ password
+ "].And check the network connection is working or if the request was denied by the firewall:"
+ jse.getMessage());
}
}
/**
* 断开(销毁)Sessioin
*/
public void disSession() {
if (session != null) {
session.disconnect();
session = null;
}
}
/**
* 获得SFTP连接
*
* @return
* @throws JSchException
*/
private ChannelSftp getChannelSftp() throws JSchException {
// 打开SFTP连接通道
Channel channel = session.openChannel("sftp");
try {
// 打开渠道连接
channel.connect();
} catch (JSchException jse) {
// 如果连接已打开,需要销毁连接
if (channel.isConnected()) {
channel.disconnect();
}
throw new JSchException(
"Connect to the server failed.Please check HOST["
+ host
+ "],PORT["
+ port
+ "],USERNAME["
+ username
+ "],PASSWORD["
+ password
+ "].And check the network connection is working or if the request was denied by the firewall:"
+ jse.getMessage());
}
ChannelSftp channelSftp = (ChannelSftp) channel;
return channelSftp;
}
/**
* 断开(销毁)SFTP连接
*/
private void disChannelSftp(ChannelSftp channelSftp) {
if (channelSftp != null) {
channelSftp.disconnect();
channelSftp.exit();
channelSftp = null;
}
}
/**
* 上传文件
*
* @param directory
* 待上传的目录(如:/finance)
* @param uploadFile
* 待上传的文件
* @param uploadFileName
* 上传文件的新文件名(FTP服务器上存储的文件名,如:EACQ_YNLF_20130615.xls)
* @throws FileNotFoundException
* 文件未不到异常
* @throws SftpException
* SFTP异常
* @throws
*/
public void upload(String directory, File uploadFile, String uploadFileName)
throws JSchException, FileNotFoundException, SftpException {
// 获得SFTP服务器连接
ChannelSftp channelSftp = null;
BufferedInputStream binput = null;
try {
channelSftp = getChannelSftp();
// 进入目录
channelSftp.cd(directory);
// 创建往本地文件中输入的流
binput = new BufferedInputStream(new FileInputStream(uploadFile));
// 上传
channelSftp.put(binput, uploadFileName);
} finally {
if (binput != null) {
try {
binput.close();
} catch (IOException ioe) {
}
}
// 断开(销毁)SFTP连接
disChannelSftp(channelSftp);
}
}
/**
* 下载文件
*
* @param directory
* 待下载目录(如:/finance)
* @param downloadFileName
* 待下载的文件名(EACQ_YNLF_20130615.xls)
* @param saveFile
* 下载后存入本地的文件
* @throws FileNotFoundException
* 文件未不到异常
* @throws SftpException
* SFTP异常
*/
public void download(String directory, String downloadFileName,
File saveFile) throws JSchException, FileNotFoundException,
SftpException {
ChannelSftp channelSftp = null;
BufferedOutputStream boutput = null;
try {
// 获得SFTP服务器连接
channelSftp = getChannelSftp();
// 进入目录
channelSftp.cd(directory);
// 创建往SFTP上输出的流
boutput = new BufferedOutputStream(new FileOutputStream(saveFile));
// 下载
channelSftp.get(downloadFileName, boutput);
} finally {
if (boutput != null) {
try {
boutput.close();
} catch (IOException ioe) {
}
}
// 断开(销毁)SFTP连接
disChannelSftp(channelSftp);
}
}
/**
* 删除文件. 仅支持删除文件,不支持删除目录
*
* @param directory
* 待删除文件所在目录
* @param deleteFile
* 待删除的文件(文件名全称,如:EACQ_YNLF_20130615-up.xls)
* @throws SftpException
* SFTP异常
* @throws JSchException
*/
public void delete(String directory, String deleteFile)
throws JSchException, SftpException {
ChannelSftp channelSftp = null;
try {
// 获得SFTP服务器连接
channelSftp = getChannelSftp();
// 进入目录
channelSftp.cd(directory);
// 删除文件
channelSftp.rm(deleteFile);
} finally {
// 断开(销毁)SFTP连接
disChannelSftp(channelSftp);
}
}
/**
* 列出目录下的文件
*
* @param directory
* 待列出的目录
* @return 目录中的所有文件名列表(包括后缀名,如:EACQ_YNLF_20130615.xls)
* @throws SftpException
* SFTP异常
*/
public Vector<String> listFiles(String directory) throws JSchException,
SftpException {
ChannelSftp channelSftp = null;
Vector<String> fileNameList = new Vector<String>();
try {
// 获得SFTP服务器连接
channelSftp = getChannelSftp();
Vector<Object> objectList = channelSftp.ls(directory);
for (Object obj : objectList) {
// 获取文件名(包括后缀名)
// -rw-r--r-- 1 hsm users 975872 Jul 9 03:26
// EACQ_YNLF_20130615.xls
String curStr = obj.toString();
curStr = curStr.substring(curStr.lastIndexOf(" ") + 1);
if (".".equals(curStr) || "..".equals(curStr)) {// .表示当前目录,..表示上一级目录
continue;
}
fileNameList.add(curStr);
}
} finally {
// 断开(销毁)SFTP连接
disChannelSftp(channelSftp);
}
return fileNameList;
}
/**
* 用于模糊查询某个远程目录下的文件名称. 只要文件名中包含{valiStr}即可列出
*
* @param directory
* 远程目录
* @param valiStr
* 文件名称
* @return 远程目录下的文件名称列表(包括后缀名,如:EACQ_YNLF_20130615.xls)
* @throws SftpException
* SFTP异常
*/
public Vector<String> listFileNames(String directory, String valiStr)
throws JSchException, SftpException {
ChannelSftp channelSftp = null;
Vector<String> fileNameList = new Vector<String>();
try {
// 获得SFTP服务器连接
channelSftp = getChannelSftp();
Vector<Object> objectList = channelSftp.ls(directory);
for (Object obj : objectList) {
// 获取文件名(包括后缀名)
// -rw-r--r-- 1 hsm users 975872 Jul 9 03:26
// EACQ_YNLF_20130615.xls
String curStr = obj.toString();
curStr = curStr.substring(curStr.lastIndexOf(" ") + 1);
// 检查文件名是否包含{valiStr}
if (curStr.contains(valiStr)) {
// 包含即加如Vector
fileNameList.add(curStr);
}
}
} finally {
// 断开(销毁)SFTP连接
disChannelSftp(channelSftp);
}
return fileNameList;
}
/**
* 检查文件是否存在
*
* @param directory
* 远程目录
* @param valiStr
* 文件名称
* @return 是否存在(true-存在 false-不存在)
* @throws SftpException
* SFTP异常
*/
public boolean isExists(String directory, String valiStr)
throws JSchException, SftpException {
ChannelSftp channelSftp = null;
try {
// 获得SFTP服务器连接
channelSftp = getChannelSftp();
Vector<Object> objectList = channelSftp.ls(directory);
for (Object obj : objectList) {
// 获取文件名(包括后缀名)
// -rw-r--r-- 1 hsm users 975872 Jul 9 03:26
// EACQ_YNLF_20130615.xls
String curStr = obj.toString();
curStr = curStr.substring(curStr.lastIndexOf(" ") + 1);
// 检查文件名是否包含{valiStr}
if (curStr.equals(valiStr)) {
return true;
}
}
} finally {
// 断开(销毁)SFTP连接
disChannelSftp(channelSftp);
}
return false;
}
// /**
// * 仅测试用
// *
// * @param args
// * @throws JSchException
// * @throws SftpException
// * @throws FileNotFoundException
// */
// public static void main(String[] args) {
// String IP = "10.10.110.21";
// int PORT = 22;
// String UNAME = "hsm";
// String PWD = "123321";
// String PATH = "/home/hsm/finance";
// SftpUtils utils = null;
// Vector<String> vector = null;
// try {
// utils = new SftpUtils(IP, PORT, UNAME, PWD);
// // 下载
// // utils.download("finance", "EACQ_YNLF_20130615-4.xls",
// // new File("H:\\workspace\\finance\\EACQ_YNLF_20130615-6.xls"));
// // 上传
// // utils.upload("finance", new
// // File("H:\\workspace\\finance\\EACQ_YNLF_20130615(New).xls"),
// // "EACQ_YNLF_20130615-up.xls");
// // 列出目录下的文件
// // vector = utils.listFiles("finance");
// // 用于查询某个远程目录下的文件名称
// // vector = utils.listFileNames("finance","EACQ_YNLF_20130615");
// // for (String str : vector) {
// // System.out.println(str);
// // }
// // 删除文件
// // utils.delete("finance", "test");
// } catch (Exception e) {
// e.printStackTrace();
// }
// // System.exit(0);
// }
}
FTP下载的更多相关文章
- ftp下载目录下所有文件及文件夹内(递归)
ftp下载目录下所有文件及文件夹内(递归) /// <summary> /// ftp文件上传.下载操作类 /// </summary> public class FTPH ...
- 批处理:Windows主机通过FTP下载远程Linux主机上文件
问题:在Windows上怎么写个批处理把多个文件FTP依次下载到本地某个目录. 批处理脚本示例: @echo off title Download db files. Don't close it!! ...
- (转)FTP操作类,从FTP下载文件
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net ...
- java ftp下载文件
1.使用官方正规的jar commons-net-1.4.1.jar jakarta-oro-2.0.8.jar 注意:使用ftp从windows服务器下载文件和从linux服务器下载文件不一样 2. ...
- [windows]快速从ftp下载最新软件包的批处理脚本
背景 由于敏捷开发,快速迭代,我们项目一天会有三个版本,也就意味着我一天要去获取三次软件包.我负责服务端开发,所以我经常需要去拿最新的客户端.我们的客户端放置在一个公共的ftp上面.每天频繁登陆ftp ...
- C#FTP下载文件出现远程服务器返回错误: (500) 语法错误,无法识别命令
如果下载多个文件的时候,有时候莫名其妙的出现500服务器错误,很有可能是没有设置KeepAlive 属性导致的. 出现应用程序未处理的异常:2015/1/6 11:40:56 异常类型:WebExce ...
- FTP下载导致Zip解压失败的原因
情形:网关通过FTP下载快钱对账文件时通过Apache下commons-net的commons-net-3.5.jar进行封装,对账文件中有中文和英文的文字,大部分情况下能够下载成功,而且也能解压成功 ...
- Python(x,y) 的 FTP 下载地址
因为 Python(x,y) 软件包托管在 Google code 上 https://code.google.com/p/pythonxy/,所以国内比较难下载. 这里推荐一个 FTP 下载地址:f ...
- http和ftp下载的区别
HTTP和FTP是两种网络传输协议的缩写,FTP是File Transportation Protocol(文件传输协议)的缩写,而HTTP则是Hyper Text Transportation Pr ...
- python从FTP下载文件
#!/usr/bin/python # -*- coding: utf-8 -*- """ FTP常用操作 """ from ftplib ...
随机推荐
- 配置LANMP环境(2)-- 安装ifconfig命令与安装SecureCRT
一.安装ifconfig命令 yum whatprovides ifconfig yum install net-tools 安装这个命令就是为了查看虚拟机的ip地址,SecureCRT连接必须要ip ...
- Mybatis 逆向工程 自动生成代码
Mybatis 可以通过一定的代码,自动生成包括mapper.xml.mapper.java.po等文件: 一.环境准备: 用到的JAR包如下: 文件只有两个:GenMain.java和generat ...
- libsvm以概率输出单个test样例的判别结果
在函数svmtrain和svmpredict的输入参数部分加入'-b 1'比如原先是 svmtrain -c 8.0 -g 0.0078125 a1a.scale 修改过后就是 svmtrain -b ...
- Java数据类型的转换:隐式(自动)转换与强制转换
原文链接:http://java.chinaitlab.com/base/725590.html 一些初学JAVA的朋友可能会遇到JAVA的数据类型之间转换的苦恼,例如,整数和float,double ...
- python学习【第八篇】python模块
模块与包 模块的概念 在python中一个.py文件就是一个模块. 使用模块可以提高代码的可维护性. 模块分为三种: python标准库 第三方模块 自定义模块 模块的导入方法 1.import语句 ...
- Django报:builtin_function_or_method' object is not iterable
def detail(request,hero_id): hero=models.HeroInfo.objects.get(id=hero_id) return render_to_response( ...
- 通过jdt解析spring mvc中url-类-方法的对应关系
依赖 <dependencies> <dependency> <groupId>org.eclipse.jdt</groupId> <artifa ...
- python多进程理论
什么是进程 进程:正在进行的一个过程或者说一个任务.而负责执行任务则是cpu. 举例(单核+多道,实现多个进程的并发执行): 你在一个时间段内有很多任务要做:python学习的任务,赚钱的任务,交女朋 ...
- servle 3.0 新特性之一 对上传表单的支持
1. 上传 * 上传对表单的要求: > method="post" > enctype="multipart/form-data",它的默认值是:a ...
- https-SSL请求
# coding:utf-8import requests# 禁用安全请求警告from requests.packages.urllib3.exceptions import InsecureRequ ...