Ftp访问工具类_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Ftp访问工具类

Ftp访问工具类

 2013/9/23 22:04:38  xm_koma  程序员俱乐部  我要评论(0)
  • 摘要:java开发中经常会用到ftp上传、下载指定ftp服务器的文件,这里整理一个通过apache的commons-net包访问ftp服务的工具类:packageutils;importjava.io.IOException;importjava.net.SocketException;importorg.apache.commons.net.ftp.FTPClient;importorg.apache.commons.net.ftp.FTPReply;importorg.apache.log4j
  • 标签:工具

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

class="java" name="code">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(连接超时)

?

?

上一篇: sftp协议访问工具类 下一篇: atoi
发表评论
用户名: 匿名