ChannelSftp下载目录下所有或指定文件、ChannelSftp获取某目录下所有文件名称、InputStream转File
/**
* ChannelSftp下载目录下所有或指定文件
* ChannelSftp获取某目录下所有文件名称
* InputStream转File
*/
public Map<String, File> downFile(String remoteDir) {
Map<String, File> fileMap = new HashMap<>(20);
if (StringUtil.isEmpty(remoteDir)) {
return fileMap;
}
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
Session sshSession = jsch.getSession("name", "host", 22);
sshSession.setPassword("password");
Properties sshConfig = new Properties();
//当第一次连接服务器时,自动接受新的公钥
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
//ls命令获取文件名列表
Vector vector = channelSftp.ls(remoteDir);
Iterator iterator = vector.iterator();
while (iterator.hasNext()) {
ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
//文件名称
String fileName = file.getFilename();
//todo 这里可使用if或正则不下载一些文件
InputStream inputStream = channelSftp.get(remoteDir + fileName);
if (inputStream != null) {
File newFile = new File(fileName);
//将InputStream转File
FileUtils.copyToFile(inputStream, newFile);
fileMap.put(fileName, newFile);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (channelSftp != null) {
channelSftp.exit();
}
}
return fileMap;
}
pom.xml
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.51</version>
</dependency>