代码如下
import com.jcraft.jsch.*;
import java.io.File;
import java.util.Vector;
public class DownloadRecursiveFolderFromSFTP {
static ChannelSftp channelSftp = null;
static Session session = null;
static Channel channel = null;
static String PATHSEPARATOR = "/";
public static void main(String[] args) {
String SFTPHOST = "xxx.xxx.x.xxx";
int SFTPPORT = 22;
String SFTPUSER = "xxx";
String SFTPPASS = "xxx";
String SFTPWORKINGDIR = "/root/test/11";
String LOCALDIRECTORY = "E:\\temp";
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
recursiveFolderDownload(SFTPWORKINGDIR, LOCALDIRECTORY);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (channelSftp != null)
channelSftp.disconnect();
if (channel != null)
channel.disconnect();
if (session != null)
session.disconnect();
}
}
@SuppressWarnings("unchecked")
private static void recursiveFolderDownload(String sourcePath, String destinationPath) throws SftpException {
Vector<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(sourcePath);
for (ChannelSftp.LsEntry item : fileAndFolderList) {
if (!item.getAttrs().isDir()) {
if (!(new File(destinationPath + PATHSEPARATOR + item.getFilename())).exists()
|| (item.getAttrs().getMTime() > Long
.valueOf(new File(destinationPath + PATHSEPARATOR + item.getFilename()).lastModified()
/ (long) 1000)
.intValue())) {
new File(destinationPath + PATHSEPARATOR + item.getFilename());
channelSftp.get(sourcePath + PATHSEPARATOR + item.getFilename(),
destinationPath + PATHSEPARATOR + item.getFilename());
}
} else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) {
new File(destinationPath + PATHSEPARATOR + item.getFilename()).mkdirs();
recursiveFolderDownload(sourcePath + PATHSEPARATOR + item.getFilename(),
destinationPath + PATHSEPARATOR + item.getFilename());
}
}
}
}