FTP操作工具类:
public class FTPUtil {
private final Logger logger = LoggerFactory.getLogger(FTPUtil.class);
private static String encoding = "UTF-8";
/**
* ftp客户端
*/
FTPClient ftpClient;
/**
* ftp服务器地址
*/
private String host;
/**
* ftp 端口号 默认21
*/
private int port = 21;
/**
* ftp服务器用户名
*/
private String username;
/**
* ftp服务器密码
*/
private String password;
/**
* ftp远程目录
*/
private String remoteDir;
/**
* 本地存储目录
*/
private String localDir;
/**
* 文件路径通配符 默认列出所有
*/
private String regEx = "*";
/**
* 指定要下载的文件名
*/
private String downloadFileName;
public FTPUtil setConfig(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
return this;
}
public FTPUtil setConfig(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
return this;
}
private void connectServer() throws Exception {
if (this.ftpClient == null) {
this.ftpClient = new FTPClient();
}
// 设置超时时间
this.ftpClient.setConnectTimeout(30000);
try {
// 1、连接服务器
if (!this.ftpClient.isConnected()) {
// 如果采用默认端口,可以使用client.connect(host)的方式直接连接FTP服务器
this.ftpClient.connect(this.host, this.port);
// 登录
this.ftpClient.login(this.username, this.password);
// 获取ftp登录应答码
int reply = this.ftpClient.getReplyCode();
// 验证是否登陆成功
if (!FTPReply.isPositiveCompletion(reply)) {
logger.info("未连接到FTP,用户名或密码错误。");
this.ftpClient.disconnect();
throw new RuntimeException("未连接到FTP,用户名或密码错误。");
} else {
logger.info("FTP连接成功。IP:" host "PORT:" port);
}
// 2、设置连接属性
this.ftpClient.setControlEncoding(FTPUtil.encoding);
// 设置以二进制方式传输
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
this.ftpClient.enterLocalPassiveMode();
}
} catch (Exception e) {
try {
this.ftpClient.disconnect();
} catch (IOException e1) {
}
logger.error("连接FTP服务器出现异常,参数:ip=" this.host ",port=" this.port ",user=" this.username
",password=" this.password);
}
}
public List