ChannelSftp 远程下载目录

时间:2022-05-01 14:26:00

ChannelSftp 并不直接支持远程下载目录,

直接下载, 出现 : not supported to get directory ...

需要自己实现, 我的实现如下:

/**
* @param ftp_dir
* @param local_dir
* @param sftp
* @return
*/
public int downloadDir(String ftp_dir, String local_dir, ChannelSftp sftp) {
int sum = 0;
try {
File dir = new File(local_dir);
if (dir.isFile()) {
System.err.println(" is a file already " + dir);
return -1;
}
// if (!dir.exists()) {
// dir.mkdirs();
// }
// sftp.get(ftp_dir, new FileOutputStream(dir)); try {
Vector files = sftp.ls(ftp_dir);
if (files == null) {
return 0;
}
for (Iterator<ChannelSftp.LsEntry> iterator = files.iterator(); iterator.hasNext();) {
ChannelSftp.LsEntry str = iterator.next();
String filename = str.getFilename();
if (filename.equals(".") || filename.equals("..")) {
continue;
}

// System.out.println(filename + " --- " + str.getLongname());

SftpATTRS attrs = str.getAttrs();

boolean isdir = attrs.isDir();

boolean fifo = attrs.isFifo();

				String local_file_path = local_dir + "/" + filename;
String ftp_file_path = ftp_dir + "/" + filename;
if (isdir) {
File dir2 = new File(local_file_path);
if (!dir2.exists()) {
System.out.println(" dir2.mkdir " + local_file_path);
dir2.mkdir();
} else {
boolean b = dir2.isDirectory();
if (!b) { }
}
sum += downloadDir(ftp_file_path, local_file_path, sftp);
} else {
/**
* 判断本地文件是否存在, 如何存在, 而且 大小/ 最后修改时间相同, 则不进行下载。 TODO
*/
long size = attrs.getSize();
int aTime = attrs.getATime();
int mTime = attrs.getMTime();
downloadFile(ftp_file_path, local_file_path, sftp);
sum++;
}
}
} catch (SftpException e) {
e.printStackTrace();
}
return sum;
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
}
}