/**
* 获取FTP链接
* @return
*/
public FTPClient getFTPConnect(){
Config ftpConfig = this.getConfigInfo();
FTPClient ftpClient = new FTPClient();
FTPClientConfig ftpClientConfig = new FTPClientConfig();
ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
ftpClient.configure(ftpClientConfig);
try {
if(ftpConfig.getFTP_PORT() != null && ftpConfig.getFTP_PORT() > 0){
ftpClient.connect(ftpConfig.getFTP_IP(), ftpConfig.getFTP_PORT());
}else{
ftpClient.connect(ftpConfig.getFTP_IP());
}
ftpClient.login(ftpConfig.getFTP_USERNAME(), ftpConfig.getFTP_PASSWORD());
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
ftpClient.disconnect();
System.out.println("未连接到FTP,用户名或密码错误。");
}else{
ftpClient.setControlEncoding("UTF-8");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setBufferSize(1024 * 2);
ftpClient.setDataTimeout(30 * 1000);
System.out.println("FTP登录成功!");
}
} catch (SocketException e) {
e.printStackTrace();
System.out.println("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
e.printStackTrace();
System.out.println("FTP的端口错误,请正确配置。");
}
return ftpClient;
}
/**
* 关闭FTP服务器的连接
* @param ftpClient
*/
public void FTPDisConnect(FTPClient ftpClient){
try {
//退出FTP服务器
boolean reuslt = ftpClient.logout();
if(reuslt) {
System.out.println("成功退出FTP服务器");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(ftpClient.isConnected()) {
try {
ftpClient.disconnect();// 关闭FTP服务器的连接
} catch (IOException e) {
e.printStackTrace();
System.out.println("关闭FTP服务器的连接异常!");
}
}
}
}
public void backup(){
//step1
FTPClient ftpClient = this.getFTPConnect();
try {
System.out.println(config.toString());
System.out.println(ftpClient.isConnected());
FTPFile[] files = ftpClient.listFiles();
for(FTPFile ftpFile : files){
System.out.println(ftpFile.getName());
}
} catch (Exception e) {
e.printStackTrace();
} finally{
//step5
this.FTPDisConnect(ftpClient);
}
}