SFTP是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式。SFTP是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。(来自百度的解释)
首先创建一个Util类,在类中实现如下方法:
该类的作用是建立连接FTP通道(getChannel)。
参数说明:
ftpHost:为连接FTP的ip地址
ftpPassword:连接FTP服务器的用户密码
ftpUserName:连接FTP服务器的用户名
ftpPort:连接FTP服务器的端口
timeout:连接FTP服务器的超时时间
public static ChannelSftp getChannel(String ftpHost, String ftpPassword, String ftpUserName, int ftpPort, int timeout) throws JSchException {
JSch jsch = new JSch(); // 创建JSch对象
session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根据用户名,主机ip,端口获取一个Session对象
if (ftpPassword != null) {
session.setPassword(ftpPassword); // 设置密码
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 为Session对象设置properties
session.setTimeout(timeout); // 设置timeout时间
session.connect(); // 通过Session建立链接
channel = session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
System.out.println("SFTP通道连接成功");
return (ChannelSftp) channel;
}
然后在写一个方法,该方法的作用是关闭连接通道;
public static void closeChannel() throws Exception {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
在每次操作完文件后都要调用该静态方法。
最后在创建一个下载FTP文件的Util类。
参数说明:
downPath:下载到本地文件的目录
fileName:要下载的文件名称
ftpPath:要下载文件所在的目录路径
ftpHost:为连接FTP的ip地址
ftpPassword:连接FTP服务器的用户密码
ftpUserName:连接FTP服务器的用户名
ftpPort:连接FTP服务器的端口
timeout:连接FTP服务器的超时时间这里使用的文件流的形式下载,解决读取文件不换行的问题。
public boolean readForFstp(String downPath,String fileName,String ftpUserName, String ftpPassword, String ftpPath, String ftpHost, int ftpPort,int timeout){
boolean isSucced = false;
StringBuffer resultBuffer = new StringBuffer();
InputStream in = null;
ChannelSftp channelSftp = null;
ByteArrayOutputStream writer = null;
try {
//获取操作通道
channelSftp = FTPUtil.getChannel(ftpHost, ftpPassword, ftpUserName, ftpPort, timeout);
//本地存储文件path
String localFilePath = downPath + File.separatorChar + fileName;
File file = new File(localFilePath);
BufferedWriter bw = null;
if(file.exists()){
logger.info("该文件已存在");
return isSucced;
}else{
bw = new BufferedWriter(new FileWriter(file));
channelSftp.cd(ftpPath);
in = channelSftp.get(fileName);
if (in != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String data = null;
while ((data = br.readLine()) != null) {
resultBuffer.append(data + "\r\n");
// resultBuffer.append(data + "\n");
}
System.out.println("##################下载FTP文件##################");
System.out.println(resultBuffer.toString());
bw.write(resultBuffer.toString());
}else {
logger.error("找不到指定文件");
return isSucced;
}
in.close();
bw.close();
isSucced = true;
}
} catch (Exception e) {
logger.error("xjw: 下载Ftp文件失败");
e.printStackTrace();
}finally{
try {
if(writer != null) {
writer.close();
}
FTPUtil.closeChannel();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return isSucced;
}
有以上的几个类就可以实现对FTP服务器文件的操作,在需要下载文件时调用readForFstp()方法即可。
结束