ftp的服务器有两种连接的协议,两种协议所使用的连接的工具类是不同的
ChannelSftp 和 FTPClient 的一些使用中区别:
上传文件
ChannelSftp.put(FileInputStream, fileName) ;
FtpClient.storeFile(fileName, FileInputStream);
还有需要注意的就是关闭的连接的方法,ChannelSftp需要你把 Session也关闭掉。
使用案例:
一、使用FileFTPUtil(FTP协议)
//localPath, 本地文件的路径
//fileFtpPath, 服务区文件的路径
//fileName,下载本地文件的文件名
if (!localFile.exists()) {
FTPUtil.downloadFile(localPath, fileFtpPath, fileName); // 将服务器文件下载到本地
} else {
localFile.delete();
FTPUtil.downloadFile(localPath, fileFtpPath, fileName);
}
File localFile = new File(localPath);
is = Files.newInputStream(localFile.toPath());
// 通过is文件输入流对文件的内容进行修改填充
二、使用ChannelSftp (SFTP协议)
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.49</version>
</dependency>
JSch jsch = new JSch();
// if (privateKey != null) {
// jsch.addIdentity(privateKey);// 设置私钥
// }
Session session = jsch.getSession("用户名", "ip地址", 端口号);
session.setPassword("密码");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
System.out.println("sftp = " + sftp);
fileOut = new FileOutputStream(localFile);
sftp.get(fileFtpPath, fileOut) ;