FTP下载断点续传
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Pattern;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
public class ApacheFtpUtil {
private FTPClient ftpClient;
private String strIp;
private int intPort;
private String user;
private String password;
private static Logger logger = Logger.getLogger(ApacheFtpUtil.class.getName());
/* *
* Ftp构造函数
*/
public ApacheFtpUtil(String strIp, int intPort, String user, String Password) {
this.strIp = strIp;
this.intPort = intPort;
this.user = user;
this.password = Password;
this.ftpClient = new FTPClient();
}
public ApacheFtpUtil(String strIp, int intPort) {
this.strIp = strIp;
this.intPort = intPort;
this.user = "anonymous";
this.password = "anonymous";
this.ftpClient = new FTPClient();
}
/**
* @return 判断是否登入成功
* */
public boolean connectServer() {
boolean isLogin = false;
FTPClientConfig ftpClientConfig = new FTPClientConfig();
ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
this.ftpClient.setControlEncoding("GBK");
this.ftpClient.configure(ftpClientConfig);
try {
if (this.intPort > 0) {
this.ftpClient.connect(this.strIp, this.intPort);
} else {
this.ftpClient.connect(this.strIp);
}
// FTP服务器连接回答
int reply = this.ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
this.ftpClient.disconnect();
throw new IOException("Can't connect to server '" + this.strIp + "'");
}
isLogin = this.ftpClient.login(this.user, this.password);
if(!isLogin){
closeServer();
throw new IOException("Can't login to server '" + this.strIp + "'");
}
// 设置传输协议
this.ftpClient.enterLocalPassiveMode();
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
logger.info("恭喜" + this.user + "成功登陆FTP服务器:"+ftpClient.printWorkingDirectory());
} catch (Exception e) {
e.printStackTrace();
logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
closeServer();
}
this.ftpClient.setBufferSize(1024 * 8);
this.ftpClient.setConnectTimeout(30 * 1000);
this.ftpClient.setDataTimeout(60 * 1000);
return isLogin;
}
/**
* @退出关闭服务器链接
* */
public void closeServer() {
if (null != this.ftpClient && this.ftpClient.isConnected()) {
try {
boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
if (reuslt) {
logger.info("成功退出服务器");
}
} catch (IOException e) {
e.printStackTrace();
logger.warn("退出FTP服务器异常!" + e.getMessage());
} finally {
try {
this.ftpClient.disconnect();//