FTP Client使用的是Apache Commons Net 3.3
/**
* 检查FTP上指定文件是否存在
* @param remoteFilePartNameList 文件路径
* @throws BusinessException
* @throws IOException
*/
private void checkFtpFileExist(List<String> remoteFilePartNameList) throws BusinessException, IOException {
FTPClient ftp = new FTPClient();
String serverIP = "1.1.1.1";
String serverUserName = "user";
String serverPassword = "pwd";
try {
ftp.connect(serverIP);
ftp.login(serverUserName, serverPassword);
if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
StringBuilder sb = null;
for (String remoteFileName : remoteFilePartNameList) {
InputStream inputStream = ftp.retrieveFileStream(remoteFileName);
if (inputStream == null || ftp.getReplyCode() == 550) {
// 文件不存在
if (sb == null) {
sb = new StringBuilder();
}
String[] strings = StringUtils.split(remoteFileName, Constants.SLASH);
sb.append(strings[strings.length - 1]).append(", ");
}
if (inputStream != null) {
inputStream.close();
ftp.completePendingCommand(); // 必须执行,否则在循环检查多个文件时会出错
}
}
if (sb != null && sb.length() > 2) {
sb.setLength(sb.length() - 2);
String notfoundReportPaymentIdStr = sb.toString();
log.error("FTP SERVER上未找到以下文件[" + notfoundReportPaymentIdStr + "]");
String exceptionMessage = i18nServiceImpl.queryValue("E374", "文件{0}不存在!");
throw new BusinessException(StringUtils.replace(exceptionMessage, "{0}", notfoundReportPaymentIdStr));
}
}
else {
log.error("连接FTP SERVER失败,SERVER IP[" + serverIP + "], USER NAME[" + serverUserName + "], Ftp response:" + ftp.getReplyString());
ftp.disconnect();
throw new BusinessException(i18nServiceImpl.queryValue("E373", "连接FTP失败!"));
}
ftp.logout();
}
catch (IOException e) {
log.error("连接FTP SERVER失败,SERVER IP[" + serverIP + "], USER NAME[" + serverUserName + "]", e);
throw e;
}
finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
}
catch (IOException ioe) {
// do nothing
}
}
}
}
网友评论