某些时候,在使用ftp文件传输时,可能带有SSH服务,此时可使用如下代码段进行文件的下载
//ip 帐号 密码 端口 文件地址 下载缓存地址
public static List<String> download(String host , String userName , String pass , int port ,String path,String downPath) {
logger.info("-------------------开始下载支付宝账单信息---------------");
logger.info("关键字【"+host+"】【"+userNaem+"】【"+pass+"】【"+port+"】【"+path+"】【"+downPath+"】");
ChannelSftp channelSftp = null;
List<String> loadFilePath = null;
try {
JSch jSch=new JSch();
Session session;
session = jSch.getSession(userName, host, port);
session.setPassword(pass);
Properties config=new Properties();
config.put("StrictHostKeyChecking", "no"); //取消信任选择
session.setConfig(config);
session.setTimeout(60000);
session.connect();
channelSftp=(ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
Vector vector = channelSftp.ls(path);
if(vector == null) return null;
loadFilePath = new ArrayList<String>();
for(Object obj :vector){
if(obj instanceof LsEntry){
LsEntry o = (LsEntry) obj;
String fileName = o.getFilename();
if(!StringUtils.isEmpty(fileName) && fileName.indexOf(".zip") != -1) {
logger.info("获取到可下载文件,关键字【"+fileName+"】");
File file = new File(downPath+File.separator+fileName);
if(file.exists())
{
file.delete();
Thread.sleep(1000);
} else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info(path + File.separator + fileName+" -----> " + downPath+File.separator+fileName);
channelSftp.get(path + "/" + fileName, downPath+File.separator+fileName);
loadFilePath.add(downPath+File.separator+fileName);
}
}
}
if(loadFilePath.size() < 1) return null;
} catch (Exception e) {
e.printStackTrace();
}
finally {
if(channelSftp != null) channelSftp.quit();
}
return loadFilePath;
}
所用到的Maven工具包
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>