apache.commons.NET.FTP使用小结

 啥也不说,先上代码:

/**
 * Desc:FTP工具,实现上传、下载功能
 * Author:chenza
 * Date:Feb 17, 2011 3:27:42 PM 
 **/
package com.chenza.ftp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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 org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class FTP {
	private static Logger logger = Logger.getLogger(FTP.class);
	
	protected FTPClient ftpClient = new FTPClient();
	protected String hostname;
	protected int port;
	protected String username;
	protected String password;
	protected String remoteHomeDir = ".";
	protected String fileType = "ASCII";//上传下载的文件类型:文本(ASCII)、二进制(BIN)
	protected boolean isDel = false;
	
	public FTP(){
		
	}	
	
	public FTP(String hostname, int port, String username, String password,
			String remoteHomeDir, String fileType) {
		super();
		this.hostname = hostname;
		this.port = port;
		this.username = username;
		this.password = password;
		this.remoteHomeDir = remoteHomeDir;
		this.fileType = fileType;
	}



	public boolean connectFtp() {
		logger.info("connecting ftp[" + this.hostname +"] ...");
		try {
			ftpClient.connect(hostname, port);
			logger.info("connected ftp[" + this.hostname +"]!");
			ftpClient.setSoTimeout(60 * 1000);
			ftpClient.setDataTimeout(60 * 1000);
			int reply = ftpClient.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)) {
				logger.error("ftp server refused connection!");
				disconnectFtp();
				return false;
		    }
			logger.info("logining ftp[" + this.hostname +"] ...");
			ftpClient.login(username, password);
			logger.info("logined ftp[" + this.hostname +"]!");
			ftpClient.enterLocalPassiveMode();
			if(this.fileType.equals("ASCII")){
				ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
			}else if(this.fileType.equals("BIN")){
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
			}else{
				ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
			}
			ftpClient.changeWorkingDirectory(remoteHomeDir);
			return true;
		} catch(Exception e) {
			logger.error("connect ftp[" + this.hostname +"] failed,",e);
			return false;
		}
		
	}
	
	/**
	 * 把远程FTP服务器上指定目录remotePath下的文件fileName下载至本地localFilePath(包含路径信息)
	 * @param localFilePath 包含路径信息
	 * @param remotePath
	 * @param fileName
	 * @return 下载成功的文件(File对象)
	 */
	public File downloadFile(String localFilePath,String remotePath,String fileName) {
		File toDownloadFile = null;
		OutputStream out = null;
		try {
			logger.info("downloading from remote server[" + this.hostname +"]: " + remotePath + "/" + fileName);
			toDownloadFile = new File(localFilePath);
			//toDownloadFile.deleteOnExit();
			out = new BufferedOutputStream(new FileOutputStream(toDownloadFile));
			ftpClient.retrieveFile(remotePath + "/" + fileName, out);
			out.close();
			logger.info("downloaded to local:" + localFilePath);
			if(this.isDel){
				if(ftpClient.deleteFile(remotePath + "/" + fileName)){
					logger.info("Delete the file from the FTP Server Successful!!! ");
				}else{
					logger.info("Delete the file from the FTP Server Fail!!! ");
				}
			}
			return toDownloadFile;
		} catch(Exception e) {
			logger.error("download file failed",e);
			if(toDownloadFile != null) {
				toDownloadFile.delete();
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e1) {
					logger.error("",e1);
				}
			}
			return null;
		}
	}
	
	/**
	 * 把本地文件localFilePath上传至远程FTP服务器指定目录remotePath下,并保存为fileName文件名
	 * @param localFilePath 包含路径信息
	 * @param remotePath
	 * @param fileName
	 * @return 上传成功,返回true,反之false。
	 */
	public boolean uploadFile(String localFilePath,String remotePath,String fileName){
		File toUploadFile = null;
		InputStream in = null;
		boolean isOK = false;
		try {
			logger.info("uploading to remote server[" + this.hostname +"]:" + remotePath + "/" + fileName);
			toUploadFile = new File(localFilePath);
			in = new BufferedInputStream(new FileInputStream(toUploadFile));
			/*
			for(FTPFile file : ftpClient.listFiles(remotePath)){
				if(fileName.equals(file.getName())){
					ftpClient.deleteFile(remotePath + "/" + fileName);
					break;
				}
			}
			*/
			isOK = ftpClient.storeFile(remotePath + "/" + fileName, in); 
			in.close();
			logger.info("File upload successful!");
		} catch (Exception e) {
			logger.error("upload file failed!",e);
			if(in != null){
				try {
					in.close();
				} catch (IOException e1) {
					logger.error("",e1);
				}
			}
			isOK = false;
		}		
		return isOK;
	}
	
	public void disconnectFtp() {
		if(ftpClient != null & ftpClient.isConnected()) {
			try {
				logger.info("logout ftp[" + this.hostname +"]...");
				if(ftpClient.logout()) {
					logger.info("logouted ftp[" + this.hostname +"]!");
				} else {
					logger.error("logout ftp[" + this.hostname +"] failed");
				}
			} catch(Exception e) {
				logger.error("logout ftp[" + this.hostname +"] failed",e);
			}
			try {
				logger.info("disconnecting ftp[" + this.hostname +"] ...");
				ftpClient.disconnect();
				logger.info("disconnected ftp[" + this.hostname +"]!");
			} catch (IOException e) {
				logger.error("ftp[" + this.hostname +"] disconnect failed",e);
			}
		}
	}
	
	
	
	public String getHostname() {
		return hostname;
	}

	public void setHostname(String hostname) {
		this.hostname = hostname;
	}

	public int getPort() {
		return port;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

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

	public String getRemoteHomeDir() {
		return remoteHomeDir;
	}

	public void setRemoteHomeDir(String remoteHomeDir) {
		this.remoteHomeDir = remoteHomeDir;
	}
	
	

	public String getFileType() {
		return fileType;
	}

	public void setFileType(String fileType) {
		this.fileType = fileType;
	}

	public FTPClient getFtpClient() {
		return ftpClient;
	}

	public void setFtpClient(FTPClient ftpClient) {
		this.ftpClient = ftpClient;
	}

	public boolean isDel() {
		return isDel;
	}

	public void setDel(boolean isDel) {
		this.isDel = isDel;
	}

	
	
}

在使用过程中,需要注意的事项:(所使用的包:commons.NET.1.4.1.jar)

当登录成功后,有可能会发现找不到你想下载的文件,这时候需要确认你登录后的当前目录是什么,需用利用
ftpClient.changeWorkingDirectory(“你的用户主目录”)进行处理。

FTPClient类有这样一个方法:listFiles(pathname),这个方法在不同的平台下,获得的结果不同,具体视各FTP服务器而定。

目前本人发现了2种结果:a.列出访目录下的所有文件;b.列出与pathname同名的文件(目录)。

下面是JavaDoc上的描述:

listFiles

public FTPFile[] listFiles(String pathname)
                    throws IOException
Using the default system autodetect mechanism, obtain a list of file information for the current working directory or for just a single file.

This information is obtained through the LIST command. The contents of the returned array is determined by the FTPFileEntryParserused.

Parameters:
pathname - The file or directory to list. Since the server may or may not expand glob expressions, using them here is not recommended and may well cause this method to fail.
Returns:
The list of file information contained in the given path in the format determined by the autodetection mechanism

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值