关闭

FTP客户端工具代码

标签: ftp
984人阅读 评论(0) 收藏 举报
分类:

1.java代码

package com.diyvc.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * FTP客户端工具
 */
public class FTPClientUtil {

	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(FTPClientUtil.class);

	/**
	 * FTP server configuration--IP key,value is type of String
	 */
	public static final String SERVER_IP = "SERVER_IP";

	/**
	 * FTP server configuration--Port key,value is type of Integer
	 */
	public static final String SERVER_PORT = "SERVER_PORT";

	/**
	 * FTP server configuration--ANONYMOUS Log in key, value is type of Boolean
	 */
	public static final String IS_ANONYMOUS = "IS_ANONYMOUS";

	/**
	 * user name of anonymous log in
	 */
	public static final String ANONYMOUS_USER_NAME = "anonymous";

	/**
	 * password of anonymous log in
	 */
	public static final String ANONYMOUS_PASSWORD = "";

	/**
	 * FTP server configuration--log in user name, value is type of String
	 */
	public static final String USER_NAME = "USER_NAME";

	/**
	 * FTP server configuration--log in password, value is type of String
	 */
	public static final String PASSWORD = "PASSWORD";

	/**
	 * FTP server configuration--PASV key, value is type of Boolean
	 */
	public static final String IS_PASV = "IS_PASV";

	/**
	 * FTP server configuration--working directory key, value is type of String While logging in, the current directory
	 * is the user's home directory, the workingDirectory must be set based on it. Besides, the workingDirectory must
	 * exist, it can not be created automatically. If not exist, file will be uploaded in the user's home directory. If
	 * not assigned, "/" is used.
	 */
	public static final String WORKING_DIRECTORY = "WORKING_DIRECTORY";
	

	public static Map<String, Object> serverCfg = new HashMap<String, Object>();
	
	static Properties prop;
	
	static{
		LOGGER.info("开始加载ftp.properties文件!");
		prop = new Properties();
		try {
			InputStream fps = FTPClientUtil.class.getResourceAsStream("/ftp.properties");
			prop.load(fps);
			fps.close();
		} catch (Exception e) {
			LOGGER.error("读取ftp.properties文件异常!",e);
		}
		serverCfg.put(FTPClientUtil.SERVER_IP, values("SERVER_IP"));
		serverCfg.put(FTPClientUtil.SERVER_PORT, Integer.parseInt(values("SERVER_PORT")));
		serverCfg.put(FTPClientUtil.USER_NAME, values("USER_NAME"));
		serverCfg.put(FTPClientUtil.PASSWORD, values("PASSWORD"));
		LOGGER.info(String.valueOf(serverCfg));
	}

	/**
	 * Upload a file to FTP server.
	 * 
	 * @param serverCfg : FTP server configuration
	 * @param filePathToUpload : path of the file to upload
	 * @param fileStoredName : the name to give the remote stored file, null, "" and other blank word will be replaced
	 *            by the file name to upload
	 * @throws IOException
	 * @throws SocketException
	 */
	public static final void upload(Map<String, Object> serverCfg, String filePathToUpload, String fileStoredName)
			throws SocketException, IOException {
		upload(serverCfg, new File(filePathToUpload), fileStoredName);
	}

	/**
	 * Upload a file to FTP server.
	 * 
	 * @param serverCfg : FTP server configuration
	 * @param fileToUpload : file to upload
	 * @param fileStoredName : the name to give the remote stored file, null, "" and other blank word will be replaced
	 *            by the file name to upload
	 * @throws IOException
	 * @throws SocketException
	 */
	public static final void upload(Map<String, Object> serverCfg, File fileToUpload, String fileStoredName)
			throws SocketException, IOException {
		if (!fileToUpload.exists()) {
			throw new IllegalArgumentException("File to upload does not exists:" + fileToUpload.getAbsolutePath());
		}
		if (!fileToUpload.isFile()) {
			throw new IllegalArgumentException("File to upload is not a file:" + fileToUpload.getAbsolutePath());
		}
		if (StringUtils.isBlank((String) serverCfg.get(SERVER_IP))) {
			throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration.");
		}
		transferFile(true, serverCfg, fileToUpload, fileStoredName, null, null);
	}

	/**
	 * Download a file from FTP server
	 * 
	 * @param serverCfg : FTP server configuration
	 * @param fileNameToDownload : file name to be downloaded
	 * @param fileStoredPath : stored path of the downloaded file in local
	 * @throws SocketException
	 * @throws IOException
	 */
	public static final void download(Map<String, Object> serverCfg, String fileNameToDownload, String fileStoredPath)
			throws SocketException, IOException {
		if (StringUtils.isBlank(fileNameToDownload)) {
			throw new IllegalArgumentException("File name to be downloaded can not be blank.");
		}
		if (StringUtils.isBlank(fileStoredPath)) {
			throw new IllegalArgumentException("Stored path of the downloaded file in local can not be blank.");
		}
		if (StringUtils.isBlank((String) serverCfg.get(SERVER_IP))) {
			throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration.");
		}
		transferFile(false, serverCfg, null, null, fileNameToDownload, fileStoredPath);
	}

	private static final void transferFile(boolean isUpload, Map<String, Object> serverCfg, File fileToUpload,
			String serverFileStoredName, String fileNameToDownload, String localFileStoredPath) throws SocketException,
			IOException {
		String host = (String) serverCfg.get(SERVER_IP);
		Integer port = (Integer) serverCfg.get(SERVER_PORT);
		Boolean isAnonymous = (Boolean) serverCfg.get(IS_ANONYMOUS);
		String username = (String) serverCfg.get(USER_NAME);
		String password = (String) serverCfg.get(PASSWORD);
		Boolean isPASV = (Boolean) serverCfg.get(IS_PASV);
		String workingDirectory = (String) serverCfg.get(WORKING_DIRECTORY);
		FTPClient ftpClient = new FTPClient();
		InputStream fileIn = null;
		OutputStream fileOut = null;
		try {
			if (port == null) {
				LOGGER.debug("Connect to FTP server on " + host + ":" + FTP.DEFAULT_PORT);
				ftpClient.connect(host);
			} else {
				LOGGER.debug("Connect to FTP server on " + host + ":" + port);
				ftpClient.connect(host, port);
			}
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				LOGGER.error("FTP server refuses connection");
				return;
			}

			if (isAnonymous != null && isAnonymous) {
				username = ANONYMOUS_USER_NAME;
				password = ANONYMOUS_PASSWORD;
			}
			LOGGER.debug("Log in FTP server with username = " + username + ", password = " + password);
			if (!ftpClient.login(username, password)) {
				LOGGER.error("Fail to log in FTP server with username = " + username + ", password = " + password);
				ftpClient.logout();
				return;
			}

			// Here we will use the BINARY mode as the transfer file type,
			// ASCII mode is not supportted.
			LOGGER.debug("Set type of the file, which is to upload, to BINARY.");
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

			if (isPASV != null && isPASV) {
				LOGGER.debug("Use the PASV mode to transfer file.");
				ftpClient.enterLocalPassiveMode();
			} else {
				LOGGER.debug("Use the ACTIVE mode to transfer file.");
				ftpClient.enterLocalActiveMode();
			}

			if (StringUtils.isBlank(workingDirectory)) {
				workingDirectory = "/";
			}
			
			LOGGER.debug("Change current working directory to " + workingDirectory);
			changeWorkingDirectory(ftpClient,workingDirectory);
			
			if (isUpload) { // upload
				if (StringUtils.isBlank(serverFileStoredName)) {
					serverFileStoredName = fileToUpload.getName();
				}
				fileIn = new FileInputStream(fileToUpload);
				LOGGER.debug("Upload file : " + fileToUpload.getAbsolutePath() + " to FTP server with name : "
						+ serverFileStoredName);
				if (!ftpClient.storeFile(serverFileStoredName, fileIn)) {
					LOGGER.error("Fail to upload file, " + ftpClient.getReplyString());
				} else {
					LOGGER.debug("Success to upload file.");
				}
			} else { // download
				// make sure the file directory exists
				File fileStored = new File(localFileStoredPath);
				if (!fileStored.getParentFile().exists()) {
					fileStored.getParentFile().mkdirs();
				}
				fileOut = new FileOutputStream(fileStored);
				LOGGER.debug("Download file : " + fileNameToDownload + " from FTP server to local : "
						+ localFileStoredPath);
				if (!ftpClient.retrieveFile(fileNameToDownload, fileOut)) {
					LOGGER.error("Fail to download file, " + ftpClient.getReplyString());
				} else {
					LOGGER.debug("Success to download file.");
				}
			}

			ftpClient.noop();

			ftpClient.logout();

		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
				}
			}
			if (fileIn != null) {
				try {
					fileIn.close();
				} catch (IOException e) {
				}
			}
			if (fileOut != null) {
				try {
					fileOut.close();
				} catch (IOException e) {
				}
			}
		}
	}
	
	private static final boolean changeWorkingDirectory(FTPClient ftpClient, String workingDirectory) throws IOException{
		if(!ftpClient.changeWorkingDirectory(workingDirectory)){
			String [] paths = workingDirectory.split("/");
			for(int i=0 ;i<paths.length ;i++){
				if(!"".equals(paths[i])){
					if(!ftpClient.changeWorkingDirectory(paths[i])){
						ftpClient.makeDirectory(paths[i]);
						ftpClient.changeWorkingDirectory(paths[i]);
					}
				}
			}
		}
		return true;
	}
	
	public static final void upload(Map<String, Object> serverCfg, String filePathToUpload, String fileStoredPath, String fileStoredName)
			throws SocketException, IOException {
		upload(serverCfg, new File(filePathToUpload), fileStoredPath, fileStoredName);
	}
	
	public static final void upload(Map<String, Object> serverCfg, File fileToUpload, String fileStoredPath, String fileStoredName)
			throws SocketException, IOException {
		if(fileStoredPath!=null && !"".equals(fileStoredPath)){
			serverCfg.put(WORKING_DIRECTORY, fileStoredPath);
		}
		upload(serverCfg, fileToUpload, fileStoredName);
	}
	
	public static final void upload(String filePathToUpload, String fileStoredPath)throws SocketException, IOException {
		upload(serverCfg, filePathToUpload, fileStoredPath, "");
	}
	
	public static final void upload(File fileToUpload, String fileStoredPath)throws SocketException, IOException {
		upload(serverCfg, fileToUpload, fileStoredPath, "");
	}
	


	
	public static String values(String key) {
		String value = prop.getProperty(key);
		if (value != null) {
			return value;
		} else {
			return null;
		}
	}
	
}

2.ftp.properties配置文件

#服务器地址
#测试环境
SERVER_IP=192.168.1.00
#正式环境
#SERVER_IP=10.1XX.XX.XXX

#服务器端口
#测试环境
SERVER_PORT=21
#正式环境
#SERVER_PORT=21

#帐号名
#测试环境
USER_NAME=XXXXXX
#正式环境
#USER_NAME=XXXXXX

#密码
#测试环境
PASSWORD=12345678a
#正式环境
#PASSWORD=12345678a


0
0
查看评论

FTP测试工具

下载地址 最近写了个FTP测试工具,可以对FTP服务器甚至其他行文本协议的服务器,例如HTTP、SMTP等,进行测试。 原本只是写一个具有简单收发功能的小程序,但是FTP里面端口号的计算很烦,因此该程序可以自动生成PORT命令,和自动分析PASV回复,并自动连接到被动端口上。&#...
  • sonicling
  • sonicling
  • 2009-09-07 09:19
  • 4786

最全的ftp 操作工具(所有方法经过测试,附ftp 服务配置)

1、前言 ftp 配置详解,参照前面的博文,这里有一份例子是关于配置在数据库的 http://download.csdn.net/detail/ice_grey/8525957 2、ftp 操作工具类 自己个人开发用到的,网上有许多,代码部分来源网上,但好象都有路径中文问题,或者其他问题...
  • ice_grey
  • ice_grey
  • 2015-03-23 17:20
  • 2930

FTP测试工具

  • 2012-03-22 13:46
  • 1.06MB
  • 下载

ftp绿色测试工具下载

  • 2011-06-22 09:42
  • 3.23MB
  • 下载

FTP客户端代码解析

FTP协议程序设计客户端分析程序流程思路ftp程序有两个tcp连接,一个是控制连接,一个是数据连接。控制连接负责命令的传输和应答,数据连接负责传输文件数据。用户通过客户端的用户接口输入命令,然后通过客户端协议解释后发送命令,服务器端接到命令返回应答,客户端收到后再解析处理,显示出来。一、建立控制连接...
  • wuyueqiuku
  • wuyueqiuku
  • 2016-06-21 13:55
  • 688

使用 Socket 通信实现 FTP 客户端程序

今天在用到FTP编程,在IBM developerWorks看到一篇很好的文档,果断转过来,原文地址-http://www.ibm.com/developerworks/cn/linux/l-cn-socketftp/ 使用 Socket 通信实现 FTP 客户端程序 FTP 客户端...
  • luoqindong
  • luoqindong
  • 2016-05-19 09:57
  • 5146

java ftp客户端源代码

自己写了一个简单的ftp客户端,这个客户端主要使用的是FtpClient这个类,这个类处于jdk的lib/rt.jar包中。现在实现了文件上传,文件夹上传。其余的功能有待补充。代码如下:import java.io.File;import java.io.FileInputStream;import...
  • webkkk
  • webkkk
  • 2007-07-25 10:34
  • 5451

linux下用C编写ftp客户端

这是一个大作业,要求能够模拟ftp协议,实现一个ftp客户端,然后要求能够实现相应的功能,主要是能够实现ls,pwd,cwd(cd),put和get功能。然后是在被动模式下来实现这些功能。那么首先我们需要对ftp协议有一个具体的了解,然后才能够自己实现这个功能。 FTP 概述 文...
  • sun_wangdong
  • sun_wangdong
  • 2015-05-20 11:27
  • 6419

FTP客户端源代码

  • 2013-01-09 10:22
  • 622KB
  • 下载

FTP客户端源代码实现

  • 2012-02-17 11:07
  • 801KB
  • 下载
    个人资料
    • 访问:355778次
    • 积分:5057
    • 等级:
    • 排名:第6578名
    • 原创:166篇
    • 转载:69篇
    • 译文:0篇
    • 评论:62条
    最新评论