使用SFTP连接方式下载文件
JAR包jcraft:
/**
*
* 密钥文件连接
*
* @param port 端口号 如: "22"
* @param priKeyFile 密钥文件地址(注意是地址)
* @param passphrase 密码(为空也可以,直接用秘钥操作)
* @param downloadFile 下载地址
* @param saveFile 保存的地址
* @param fileNames 下载的文件名
* @return
*/
public static boolean priKeyConnect(int port,String priKeyFile,String passphrase,String downloadFile,
String saveFile, List<String> fileNames,Map<String,String> downLoadFilePaths){
boolean result = true;
ChannelSftp sftp = null;
Session session = null;
Channel channel = null;
JSch jsch=new JSch();
try {
if(priKeyFile !=null && !"".equals(priKeyFile)){
if(passphrase !=null && !"".equals(passphrase)){
jsch.addIdentity(priKeyFile, passphrase);
}else{
jsch.addIdentity(priKeyFile);
}
}
if(port >0){
session=jsch.getSession(FTP_USERNAME, FTP_IP, FTP_PORT);
}else{
session=jsch.getSession(FTP_USERNAME, FTP_IP);
}
Properties config=new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(FTP_DEFAULT_TIMEOUT_SECOND);
session.connect();
channel=session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp)channel;
} catch (Exception e) {
e.printStackTrace();
logger.info("SFTP连接失败");
result = false;
}
if(result){
try {
for (String directory : fileNames){//循环文件下载
File srcFile = new File(saveFile+File.separator+directory);
if(!srcFile.exists()){
(new File(srcFile.getParent())).mkdirs();
}
sftp.cd(downloadFile);//进入下载地址
sftp.get(directory,saveFile);//目标文件和保存地址
downLoadFilePaths.put(directory, srcFile.getPath());
}
}catch (Exception e){
e.printStackTrace();
logger.info("SFTP下载失败");
result = false;
}finally {
session.disconnect();
channel.disconnect();
sftp.disconnect();
}
}
return result;
}
下载完成后可以把源文件移到bak目录下等待下次下载,用rename 方法即可
sftp.rename(oldPath,newPath);
如果需要删除目录,用rm即可
sftp.rm(deleteFile);
如果要上传文件,用put即可
sftp.cd(remotedir);
File file=new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());