论坛首页 Java企业应用论坛

基于Apache Common-net Ftp实例

浏览 9095 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (11) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-12-09  
  本人参考Apache Common-net 2.2 的Api以及官方网的测试代码而写的FTP客户端操作

实例,还请高手多指教。

package com.shine.Ftp.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtil {

	private FTPClient ftp = null;
	/**
	 * Ftp服务器
	 */
	private String server;
	/**
	 * 用户名
	 */
	private String uname;
	/**
	 * 密码
	 */
	private String password;
	/**
	 * 连接端口,默认21
	 */
	private int port = 21;

	public FTPUtil() {

	}
	/**
	 * 连接FTP服务器
	 * 
	 * @param server
	 * @param uname
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public FTPClient connectFTPServer(String server, int port, String uname,
			String password) throws Exception {
		
		//初始化并保存信息
		this.server = server ;
		this.port = port ;
		this.uname = uname ;
		this.password = password ;
		
		ftp = new FTPClient();
		try {
			ftp.configure(getFTPClientConfig());
			ftp.connect(this.server, this.port);
			ftp.login(this.uname, this.password);

			// 文件类型,默认是ASCII
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

			// 设置被动模式
			ftp.enterLocalPassiveMode();

			ftp.setConnectTimeout(2000);
			ftp.setControlEncoding("GBK");

			// 响应信息
			int replyCode = ftp.getReplyCode();
			if ((!FTPReply.isPositiveCompletion(replyCode))) {
				// 关闭Ftp连接
				closeFTPClient();
				// 释放空间
				ftp = null;
				throw new Exception("登录FTP服务器失败,请检查![Server:" + server + "、"
						+ "User:" + uname + "、" + "Password:" + password);
			} else {
				return ftp;
			}
		} catch (Exception e) {
			ftp.disconnect();
			ftp = null;
			throw e;
		}
	}

	/**
	 * 配置FTP连接参数
	 * 
	 * @return
	 * @throws Exception
	 */
	public FTPClientConfig getFTPClientConfig() throws Exception {

		String systemKey = FTPClientConfig.SYST_NT;
		String serverLanguageCode = "zh";
		FTPClientConfig conf = new FTPClientConfig(systemKey);
		conf.setServerLanguageCode(serverLanguageCode);
		conf.setDefaultDateFormatStr("yyyy-MM-dd");

		return conf;
	}

	/**
	 * 上传文件到FTP根目录
	 * 
	 * @param localFile
	 * @param newName
	 * @throws Exception
	 */
	public void uploadFile(String localFile, String newName) throws Exception {
		InputStream input = null;
		try {
			File file = null;
			if (checkFileExist(localFile)) {
				file = new File(localFile);
			}
			input = new FileInputStream(file);
			boolean result = ftp.storeFile(newName, input);
			if (!result) {
				throw new Exception("文件上传失败!");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (input != null) {
				input.close();
			}
		}
	}

	/**
	 * 上传文件到FTP根目录
	 * 
	 * @param input
	 * @param newName
	 * @throws Exception
	 */
	public void uploadFile(InputStream input, String newName) throws Exception {
		try {
			boolean result = ftp.storeFile(newName, input);
			if (!result) {
				throw new Exception("文件上传失败!");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (input != null) {
				input.close();
			}
		}

	}

	/**
	 * 上传文件到指定的FTP路径下
	 * 
	 * @param localFile
	 * @param newName
	 * @param remoteFoldPath
	 * @throws Exception
	 */
	public void uploadFile(String localFile, String newName,
			String remoteFoldPath) throws Exception {
		InputStream input = null;
		try {
			File file = null;
			if (checkFileExist(localFile)) {
				file = new File(localFile);
			}
			input = new FileInputStream(file);

			// 改变当前路径到指定路径
			this.changeDirectory(remoteFoldPath);
			boolean result = ftp.storeFile(newName, input);
			if (!result) {
				throw new Exception("文件上传失败!");
			}

		} catch (Exception e) {
			throw e;
		} finally {
			if (input != null) {
				input.close();
			}
		}
	}

	/**
	 * 上传文件到指定的FTP路径下
	 * 
	 * @param input
	 * @param newName
	 * @param remoteFoldPath
	 * @throws Exception
	 */
	public void uploadFile(InputStream input, String newName,
			String remoteFoldPath) throws Exception {
		try {
			// 改变当前路径到指定路径
			this.changeDirectory(remoteFoldPath);
			boolean result = ftp.storeFile(newName, input);
			if (!result) {
				throw new Exception("文件上传失败!");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (input != null) {
				input.close();
			}
		}
	}

	/**
	 * 从FTP指定的路径下载文件
	 * 
	 * @param remotePath
	 * @param localPath
	 */
	public void downloadFile(String remotePath, String localPath)
			throws Exception {

		OutputStream output = null;
		try {
			File file = null;
			if (checkFileExist(localPath)) {
				file = new File(localPath);
			}
			output = new FileOutputStream(file);
			boolean result = ftp.retrieveFile(remotePath, output);
			if (!result) {
				throw new Exception("文件下载失败!");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (output != null) {
				output.close();
			}
		}

	}

	/**
	 * 从FTP指定的路径下载文件
	 * 
	 * @param remoteFilePath
	 * @return
	 * @throws Exception
	 */
	public InputStream downFile(String remoteFilePath) throws Exception {
		return ftp.retrieveFileStream(remoteFilePath);
	}

	/**
	 * 获取FTP服务器上指定路径下的文件列表
	 * 
	 * @param filePath
	 * @return
	 */
	public List<String> getFtpServerFileList(String filePath) throws Exception {
		
		List<String> nlist = new ArrayList<String>();
		FTPListParseEngine engine = ftp.initiateListParsing(filePath);
		List<FTPFile> ftpfiles = Arrays.asList(engine.getNext(25));
		
		return getFTPServerFileList(nlist,ftpfiles);
	}

	/**
	 * 获取FTP服务器上指定路径下的文件列表
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public List<String> getFileList(String path) throws Exception {
		
		List<String> nlist = new ArrayList<String>();
		List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles(path));
		
		return getFTPServerFileList(nlist,ftpfiles);
	}
	
	/**
	 * 列出FTP服务器文件列表信息
	 * @param nlist
	 * @param ftpFiles
	 * @return
	 */
	public List<String> getFTPServerFileList(List<String> nlist,List<FTPFile> ftpFiles){
		if(ftpFiles==null || ftpFiles.size()==0)
			return nlist;
		for (FTPFile ftpFile : ftpFiles) {
			if (ftpFile.isFile()) {
				nlist.add(ftpFile.getName());
			}
		}
		return nlist;
	}
	

	/**
	 * 改变工作目录,如失败则创建文件夹
	 * 
	 * @param remoteFoldPath
	 */
	public void changeDirectory(String remoteFoldPath) throws Exception {

		if (remoteFoldPath != null) {
			boolean flag = ftp.changeWorkingDirectory(remoteFoldPath);
			if (!flag) {
				ftp.makeDirectory(remoteFoldPath);
				ftp.changeWorkingDirectory(remoteFoldPath);
			}
		}

	}

	/**
	 * 检查文件是否存在
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public boolean checkFileExist(String filePath) throws Exception {
		boolean flag = false;
		File file = new File(filePath);
		if (!file.exists()) {
			throw new Exception("文件不存在,请检查!");
		} else {
			flag = true;
		}
		return flag;
	}

	/**
	 * 获取文件名,不包括后缀
	 * 
	 * @param filePath
	 * @return
	 */
	public String getFileNamePrefix(String filePath) throws Exception {

		boolean flag = this.checkFileExist(filePath);
		if (flag) {
			File file = new File(filePath);
			String fileName = file.getName();
			String _fileName = fileName.substring(0, fileName.lastIndexOf("."));
			return _fileName;
		}
		return null;
	}

	/**
	 * 关闭FTP连接
	 * 
	 * @param ftp
	 * @throws Exception
	 */
	public void closeFTPClient(FTPClient ftp) throws Exception {

		try {
			if (ftp.isConnected())
				ftp.disconnect();
		} catch (Exception e) {
			throw new Exception("关闭FTP服务出错!");
		}
	}

	/**
	 * 关闭FTP连接
	 * 
	 * @throws Exception
	 */
	public void closeFTPClient() throws Exception {

		this.closeFTPClient(this.ftp);

	}

	/**
	 * Get Attribute Method
	 * 
	 */
	public FTPClient getFtp() {
		return ftp;
	}

	public String getServer() {
		return server;
	}

	public String getUname() {
		return uname;
	}

	public String getPassword() {
		return password;
	}

	public int getPort() {
		return port;
	}
	
	/**
	 *  Set Attribute Method
	 * 
	 */
	public void setFtp(FTPClient ftp) {
		this.ftp = ftp;
	}

	public void setServer(String server) {
		this.server = server;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setPort(int port) {
		this.port = port;
	}

	/**
	 * 主方法(测试)
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			FTPUtil fu = new FTPUtil();
			fu.connectFTPServer("192.168.11.28", 21, "Ftpuser", "sunshine");
					} catch (Exception e) {
			System.out.println("异常信息:" + e.getMessage());
		}
	}
}

   发表时间:2011-12-09  
提供断点续传的实现
0 请登录后投票
   发表时间:2012-01-04  
当出现:FTP times out

解决方向:The TCP port usually used for FTP connection is port 21. Most often the reason for FTP time out is that your firewall or Internet service provider blocks this port or because your FTP client is NOT set to use Passive mode.  First of all you should make sure that you use Passive mode with your FTP client. Then, if the problem persists,  you should run a check of the connection between your computer and the port 21. If there is a problem with the connectivity you should try disabling your local firewall, or, if this does not help, you should contact your Internet Service Provider.

试试:ftp.enterLocalActiveMode();







0 请登录后投票
   发表时间:2012-01-04  
How to check whether FTP port 21 is blocked?


The default TCP port for FTP connection is port 21. Sometimes the local Internet Service Provider blocks this port and this will result in FTP connection issues.

Here's how to, depending on your OS, check whether your ISP blocks port 21:

Check port 21 with a Windows OS
Click on the Start menu button, usually located on the left low corner of the screen. There is a tab called "Run". You have to click on it, in order to proceed further. You will notice the appearance of a new small window on the screen. In the text field of this window you need to type "cmd" and then press the "Enter" key. Another window will open. It is the so called "MS-DOS prompt" or "command prompt". Just type the following command in the command prompt window and press "Enter":

telnet my-domain-name.com 21

Check port 21 with Apple/Mac
Each Mac OS is delivered with a preinstalled terminal emulator. The terminal is a tool which allows you to execute commands from the command line. Usually, the terminal is located under your Mac HD -> "Applications" directory -> Utilities sub-directory. When the window opens, you will see a command line with a flashing cursor on it so you can start typing right away. Just type the following command and press "Enter":

telnet my-domain-name.com 21

Check port 21 with Linux
Open your favorite terminal emulator and execute the following command in order to telnet your website:

telnet my-domain-name.com 21

Results from the 21 port check
If the test is successful, you should receive a message like this:


220---------- Welcome to Pure-FTPd [TLS] ----------
220-You are user number 2 of 50 allowed.
220-<<
220-#########################################################
220-Please upload your web files to the public_html directory.
220-Note that letters are case sensitive.
220-#########################################################
220->>
220-Local time is now 03:35. Server port: 21.
220-This is a private system - No anonymous login
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.


If the welcome message above does not appear, you should contact your local ISP and ask them to unblock this port for you.

SiteGround provides the best FTP hosting services and we will help you with any FTP questions or problems you might have.


0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics