import org.apache.commons.net.ftp.FTPClient; //导入方法依赖的package包/类
/**
* 执行FTP回调操作的方法
*
* @param the type parameter
* @param callback 回调的函数
* @return the t
* @throws IOException the io exception
*/
public T execute(FTPClientCallback callback) throws IOException {
FTPClient ftp = new FTPClient();
try {
//登录FTP服务器
try {
//设置超时时间
ftp.setDataTimeout(7200);
//设置默认编码
ftp.setControlEncoding(DEAFULT_REMOTE_CHARSET);
//设置默认端口
ftp.setDefaultPort(DEAFULT_REMOTE_PORT);
//设置是否显示隐藏文件
ftp.setListHiddenFiles(false);
//连接ftp服务器
if (StringUtils.isNotEmpty(port) && NumberUtils.isDigits(port)) {
ftp.connect(host, Integer.valueOf(port));
} else {
ftp.connect(host);
}
} catch (ConnectException e) {
logger.error("连接FTP服务器失败:" + ftp.getReplyString() + ftp.getReplyCode());
throw new IOException("Problem connecting the FTP-server fail", e);
}
//得到连接的返回编码
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
}
//登录失败权限验证失败
if (!ftp.login(getUsername(), getPassword())) {
ftp.quit();
ftp.disconnect();
logger.error("连接FTP服务器用户或者密码失败::" + ftp.getReplyString());
throw new IOException("Cant Authentificate to FTP-Server");
}
if (logger.isDebugEnabled()) {
logger.info("成功登录FTP服务器:" + host + " 端口:" + port);
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
//回调FTP的操作
return callback.doTransfer(ftp);
} finally {
//FTP退出
ftp.logout();
//断开FTP连接
if (ftp.isConnected()) {
ftp.disconnect();
}
}
}