现有需求将文件从FTP服务器上进行上传下载,看网上使用了org.apache.commons.net.ftp.FTPClient类,但通过该类连接FTP会报一个Could not parse response code.Server Reply: SSH-2.0-OpenSSH_5.3这样的错误,原因是它不支持这种方式的连接(使用FTPSClient的SSL也是不行的),所以现在换新的工具,使用ChannelSftp来实现该功能。
上代码:根据实际情况略作修改
pom文件:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
默认编码是UTF-8
@Slf4j
@Component
public class FtpJSch {
/*
缺关闭连接
*/
private static ChannelSftp sftp = null;
private static Channel channel=null;
private static Session sshSession=null;
//账号
private static String user = "";
//主机ip
private static String host = "";
//密码
private static String password = "";
//端口
private static int port = 22;
//上传地址
private static String directory = "";
//下载目录
private static String saveFile = "";
public static void getConnect(){
try {
JSch jsch = new JSch();
//获取sshSession 账号-ip-端口
sshSession =jsch.getSession(user, host,port);
//添加密码
sshSession.setPassword(password);
Properties sshConfig = new Properties();
//严格主机密钥检查
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
//开启sshSession链接
sshSession.connect();
//获取sftp通道
channel = sshSession.openChannel("sftp");
//开启
channel.connect();
sftp = (ChannelSftp) channel;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param uploadFile 上传文件的路径
* @return 服务器上文件名
*/
public String upload(String uploadFile) {
getConnect();
File file = null;
String fileName = null;
try {
sftp.cd(directory);
file = new File(uploadFile);
//获取随机文件名
fileName = UUID.randomUUID().toString() + file.getName().substring(file.getName().length()-5);
//文件名是 随机数加文件名的后5位
sftp.put(new FileInputStream(file), fileName);
} catch (Exception e) {
e.printStackTrace();
}
closeChannel(channel);
closeSession(sshSession);
return file == null ? null : fileName;
}
/**
* 下载文件
*/
public void download(String downloadFileName) {
try {
getConnect();
sftp.cd(directory);
File file = new File(saveFile+File.separator+downloadFileName);
sftp.get(downloadFileName, new FileOutputStream(file));
closeChannel(channel);
closeSession(sshSession);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除文件
*
* @param deleteFile
* 要删除的文件名
*/
public void delete(String deleteFile) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 列出目录下的文件
*
* 要列出的目录
* @return
* @throws SftpException
*/
public Vector listFiles()
throws SftpException {
getConnect();
Vector ls = sftp.ls(directory);
closeChannel(channel);
closeSession(sshSession);
return ls;
}
private static void closeChannel(Channel channel) {
if (channel != null) {
if (channel.isConnected()) {
channel.disconnect();
}
}
}
private static void closeSession(Session session) {
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
}