ftp下载方法
public int downloadFtpFiles(String ftpAddr,String ftpUser,String ftpPass,String localPath,String fileTimestamp,String logFileName, boolean overwrite) throws ServiceException {
if(StringUtils.isEmpty(ftpAddr)) {
logger.warn("no ftp server!");
return 0;
}
if(!ftpAddr.endsWith("/") && !ftpAddr.endsWith("\\"))
ftpAddr += "/";
int fileNum=0;
FTPClient ftpClient = new FTPClient();
ftpClient.addListParser(new Window2003ListParser());
String remotePath = ftpAddr+fileTimestamp+"/";
try {
URL url = new URL(remotePath);
if("ftp".equalsIgnoreCase(url.getProtocol())) {
logger.debug("connecting ftp server "+ftpAddr+" ...");
ftpClient.connect(url.getHost(), url.getPort()>0?url.getPort():21);
logger.debug("login to ftp server ...");
ftpClient.login(ftpUser, ftpPass);
logger.debug("change to "+url.getPath()+" ...");
try {
ftpClient.changeDirectory(url.getPath());
} catch (Exception e) {
//e.printStackTrace();
logger.error(e,e.fillInStackTrace()); // 可能目录不存在
return 0;
}
// 遍历并下载文件
logger.debug("list files ");
FTPFile[] ftpFiles = ftpClient.list(); // 缺省按字典顺序排序
for (int i = 0; i < ftpFiles.length; i++) {
FTPFile ftpFile = ftpFiles[i];
if (ftpFile==null || ftpFile.getType()!=FTPFile.TYPE_FILE) continue;
logger.debug("downloading file "+ftpFile.getName()+"...");
ftpClient.setType(FTPClient.TYPE_BINARY); // TYPE_AUTO TYPE_TEXTUAL TYPE_BINARY
File localFile = new File(localPath+fileTimestamp+"/"+ftpFile.getName());
if(overwrite || !localFile.exists()){
ftpClient.download(ftpFile.getName(), localFile);
if(cicapFileLogExport!=null){
cicapFileLogExport.save("下载"+remotePath+ftpFile.getName(), logFileName);
}
fileNum++;
}
}
}
logger.debug("下载文件数:"+fileNum);
} catch (Exception e) {
//e.printStackTrace();
logger.error(e,e.fillInStackTrace());
throw new ServiceException("下载FTP服务器文件失败!",null,e);
}finally{
try {
ftpClient.disconnect(true);
} catch (Exception ex) {
logger.error(ex.getMessage());
}
}
return fileNum;
}