远程的服务器上下载文件,由于sftp只能下载单独的文件,于是写了一个工具类来支持可以下载单独的文件或者下载一个文件夹下所有的文件。
项目中使用了hutool的Java工具类库中的JschUtil,Sftp,StrUtil。
hutool的Java工具类库学习链接简介 | Hutool
相关工具类库引用
gradle
implementation 'com.jcraft:jsch:0.1.54'
implementation 'cn.hutool:hutool-all:5.8.16'
maven
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
工具类代码
package org.example;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.Sftp;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.util.Vector;
public class DownloadFile {
public static void downloadDir(Sftp sftp, String remotePath, String localPath) throws SftpException {
ChannelSftp channelSftp = sftp.getClient();
channelSftp.cd(remotePath);
// 列出远程文件夹下的文件列表
@SuppressWarnings("unchecked")
Vector<ChannelSftp.LsEntry> fileList = channelSftp.ls(".");
for (ChannelSftp.LsEntry file : fileList) {
if (!".".equals(file.getFilename()) && !"..".equals(file.getFilename())) {
String remoteFilePath = StrUtil.appendIfMissing(remotePath, "/") + file.getFilename();
String localFilePath = StrUtil.appendIfMissing(localPath, "/") + file.getFilename();
if (file.getAttrs().isDir()) {
File dir = new File(localFilePath);
if (!dir.exists()) {
dir.mkdirs();
}
// 如果是文件夹,递归下载
downloadDir(sftp, remoteFilePath, localFilePath);
} else {
File localFile = new File(localFilePath);
File parentFile = localFile.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
// 如果是文件,直接下载
channelSftp.get(remoteFilePath, localFilePath);
}
}
}
sftp.close();
}
}
使用demo
public class Demo {
public static void main(String[] args) throws SftpException{
String remoteFolderPath2 = "远程服务器下载文件地址";
String localFolderPath2 = "本地存放下载文件地址";
Sftp sftp= JschUtil.createSftp("远程服务器IP", 远程连接端口号, "服务器登录用户", "服务器登录密码");
DownloadFile.downloadDir(sftp,remoteFolderPath2,localFolderPath2);
}
}