Ftp访问工具类

java开发中经常会用到ftp上传、下载指定ftp服务器的文件,这里整理一个通过apache的commons-net包访问ftp服务的工具类:

package utils;

import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
 * @description
 * @author minux
 */
public class FtpUtil {

	public static final Logger logger = Logger.getLogger(FtpUtil.class);

	private String hostIp;
	private int port;
	private String dir;
	private String userName;
	private String password;
	private static final String DIR_SEPARATOR = "/";
	private FTPClient ftpClient;

	public FtpUtil() {

	}

	public FtpUtil(String hostIp, int port, String dir, String userName,
			String password) {
		this.hostIp = hostIp;
		this.port = port;
		this.dir = dir;
		this.userName = userName;
		this.password = password;
	}

	/**
	 * 连接FTP-------尝试3次
	 * 
	 * @return
	 */
	public boolean getFtpConnection() {
		int count = 0;
		boolean isConnected = false;
		while (count < 3 && !(isConnected = connectFtp())) {
			count++;
			logger.info("After a second connection again.");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return isConnected;
	}

	private boolean connectFtp() {
		try {
			ftpClient = new FTPClient();
			ftpClient.setDataTimeout(30000);
			ftpClient.setConnectTimeout(10000);
			ftpClient.connect(hostIp, port);
			if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
				logger.warn("connect to server [" + hostIp + "] fail. ");
				ftpClient.disconnect();
				return false;
			} else {
				logger.info("connect to server [" + hostIp + "] success.");
				return true;
			}
		} catch (SocketException e) {
			logger.error("ftpHost [" + hostIp
					+ "] is error, please give the correct ip: ", e);
			return false;
		} catch (IOException e) {
			logger.error("ftpPort [" + hostIp
					+ "] is error, please give the correct port: ", e);
			return false;
		}
	}

	/**
	 * 关闭FTP链接
	 */
	public void closeFtpConnection() {
		if (ftpClient.isConnected()) {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				logger.error("close FTPClient error,", e);
			}
		}
	}
}

 

 

 

用到的第三方jar:

commons-net-3.3.jar

 

目前该jar的新版本,老版本(1.4.1)会出现乱码的问题,并且不能设置一些常规参数,比如connectionTimeout(连接超时)

 

 

你可能感兴趣的:(java,ftp,网络编程,commons-net)