import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.iflytek.dicom.config.GlobalConfig;
/**
*
* ClassName: FtpUtil
* @Description: ftp工具类
* @author wyl_0728
* @date 2016年8月22日
*/
public class FtpUtil {
private static Logger logger = LogManager.getLogger(FtpUtil.class.getName());
private FTPClient ftp;
private boolean is_connected;
public FtpUtil() {
ftp = new FTPClient();
ftp.setControlEncoding("UTF-8");
ftp.enterLocalPassiveMode();
is_connected = false;
}
/*
*构造器 设置连接超时时间
*/
public FtpUtil(int defaultTimeoutSecond, int connectTimeoutSecond, int dataTimeoutSecond){
ftp = new FTPClient();
is_connected = false;
ftp.setControlEncoding("UTF-8");
ftp.enterLocalPassiveMode();
ftp.setDefaultTimeout(defaultTimeoutSecond * 1000);
ftp.setConnectTimeout(connectTimeoutSecond * 1000);
ftp.setDataTimeout(dataTimeoutSecond * 1000);
}
/**
* Connects to FTP server.
* host port username password 通过配置文件读取
*/
public FTPClient connect() throws IOException {
// Connect to server.
try {
ftp.connect(GlobalConfig.getString("FTP_SERVER"),Integer.parseInt(GlobalConfig.getString("FTP_PORT")));
} catch (UnknownHostException ex) {
throw new IOException("Can't find FTP server '" + GlobalConfig.getString("FTP_SERVER") + "'");
}
// Check rsponse after connection attempt.
int reply = ftp.getReplyCode();
logger.info("------login -reply ="+reply);
if (!FTPReply.isPositiveCompletion(reply)) {
logger.debug("---------------------##############################");
disconnect();
throw new IOException("Can't connect to server '" + GlobalConfig.getString("FTP_SERVER") + "'");
}
// Login.
boolean flag =ftp.login(GlobalConfig.getString("FTP_USER"), GlobalConfig.getString("FTP_PWD"));
logger.debug("------login -flag ="+flag);
if (!flag) {
is_connected = false;
disconnect();
throw new IOException("Can't login to server '" + GlobalConfig.getString("FTP_SERVER") + "'");
} else {
is_connected = true;
}
// Set data transfer mode.
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
logger.debug("------login -is_connected ="+is_connected);
return ftp;
}
/**
* 上传实现
* Uploads the file to the FTP server.
*
* @param ftpFileName
* server file name (with absolute path)
* @param localFile
* local file to upload
* @throws IOException
*