FTP包:commons-net-2.2.jar
public void download() throws Exception {
String filename = null;
String errorMsg = null;
try {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.connect(this.ftpDownloadItemDbo.getFtpAddress(), this.ftpDownloadItemDbo.getFtpPort());
ftpClient.login(this.ftpDownloadItemDbo.getFtpAccount(), this.ftpDownloadItemDbo.getFtpPassword());
log.info(" ---- login on ftp service success.");
ftpClient.changeWorkingDirectory("/")
String dirName = DataUtility.getStringByDate("yyyyMMdd",DataUtility.getUTCDateByLocal(new Date()));
String path = this.ftpDownloadItemDbo.getFtpFileDirectory();
if(path.trim().endsWith("/"))
dirName = path + dirName;
else
dirName = path+ "/" + dirName;
ftpClient.changeWorkingDirectory(dirName)
String fileNameRegex = this.buildRegex(this.ftpDownloadItemDbo.getFileNameFormat());
Pattern regex = Pattern.compile(fileNameRegex);
Map fileMap = new HashMap();
FTPFile[] fileDirs = ftpClient.listFiles();
for(FTPFile fileDir : fileDirs){
if(fileDir.isFile()){
filename = fileDir.getName();
Matcher regexMatcher = regex.matcher(filename);
if(regexMatcher.matches()){
fileMap.put(fileDir, filename);
}
}
}
path = path.replaceAll("/", "");
path = SystemConfig.getFTPDownloadFolderRoot() + path;
File dirFile = new File(path);
while(!fileMap.isEmpty()){
Entry file = fileMap.entrySet().iterator().next();
filename = file.getValue();
boolean repeat = false;
for(String ftpFile : fileMap.values()){
if(this.compareFileLevel(filename, ftpFile) < 0)
repeat = true;
}
if(repeat){
fileMap.remove(file.getKey());
} else{
if(!this.isExists(filename) ){
// save ftp download history
this.recordHistory(file.getKey());
if(!dirFile.exists()){
dirFile.mkdirs();
}
OutputStream out = new FileOutputStream(path + File.separator + filename);
ftpClient.retrieveFile(filename, out);
out.flush();
out.close();
}else{
fileMap.remove(file.getKey());
}
}
}
} catch(Exception e) {
// save log
this.downloadLog(filename, e.getMessage());
e.printStackTrace();
} finally {
if (ftpClient != null){
ftpClient.disconnect();
}
this.getSessionUtil().closeSession();
}
}
下载的文件数量少的时候不会出现内容为0kb的情况,批量下载时就会出现下载的文件为0KB,每次出现0KB的文件不固定
请高手们帮忙