码迷,mamicode.com
首页 > 其他好文 > 详细

FTPClientUtil FTPclient工具

时间:2017-05-18 09:51:05      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:code   name   array   hang   contains   ftps   connected   iterator   param   

package com.ctl.util;
//须要commons-net-3.0.1.jar
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.net.ftp.*;
import com.ctl.util.exception.FTPClientException;

public class FTPClientUtil {
	/** logger */
	private static ThreadLocal<FTPClient> ftpClientThreadLocal;
	// ftp ip address
	private static String host;
	// \u7AEF\u53E3\u53F7
	private static int port;
	private static String username;
	private static String password;
	private static boolean binaryTransfer;
	private static boolean passiveMode;
	// \u7F16\u7801
	private static String encoding;
	// \u8BBE\u7F6E\u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4
	private static int clientTimeout;
	// \u67E5\u8BE2\u8FDC\u7A0B\u76EE\u5F55\u6240\u6709\u7684file name
	private static List<String> listFileNames;
	// private static String filePathOfFtpserver;
	static {
		ftpClientThreadLocal = new ThreadLocal<FTPClient>();
		host = ConfigUtils.getType("ftp.host");
		port = Integer.parseInt(ConfigUtils.getType("ftp.port"));
		username = ConfigUtils.getType("ftp.username");
		password = ConfigUtils.getType("ftp.password");
		binaryTransfer = Boolean.parseBoolean(ConfigUtils
				.getType("ftp.binaryTransfer"));
		passiveMode = Boolean.parseBoolean(ConfigUtils
				.getType("ftp.passiveMode"));
		encoding = ConfigUtils.getType("ftp.encoding");
		clientTimeout = Integer.parseInt(ConfigUtils
				.getType("ftp.clientTimeout"));
		listFileNames = new ArrayList<String>();
	}
   /**
    * @description \u83B7\u53D6FTP\u5BA2\u6237\u7AEF\u8FDE\u63A5
    * @return
    * @throws FTPClientException
    * @throws SocketException
    * @throws IOException
    */
	private static FTPClient getFTPClient() throws FTPClientException,
			SocketException, IOException {
		if (ftpClientThreadLocal.get() != null
				&& ftpClientThreadLocal.get().isConnected()) {
			return ftpClientThreadLocal.get();
		} else {
			FTPClient ftpClient = new FTPClient(); // \u6784\u9020\u4E00\u4E2AFtpClient\u5B9E\u4F8B
			ftpClient.setControlEncoding(encoding); // \u8BBE\u7F6E\u5B57\u7B26\u96C6
			ftpClient.setConnectTimeout(clientTimeout);
			ftpClient.connect(host, port);
			// \u8FDE\u63A5\u540E\u68C0\u6D4B\u8FD4\u56DE\u7801\u6765\u6821\u9A8C\u8FDE\u63A5\u662F\u5426\u6210\u529F
			int reply = ftpClient.getReplyCode();
			if (FTPReply.isPositiveCompletion(reply)) {// \u767B\u9646\u5230ftp\u670D\u52A1\u5668
				ftpClient.login(username, password);
				setFileType(ftpClient); // \u8BBE\u7F6E\u6587\u4EF6\u4F20\u8F93\u7C7B\u578B
			} else {
				ftpClient.disconnect();
			}
			if (passiveMode) {
				ftpClient.enterLocalPassiveMode();
			}
			ftpClientThreadLocal.set(ftpClient);
			return ftpClient;
		}
	}

	/**
	 * @description\u8BBE\u7F6E\u6587\u4EF6\u4F20\u8F93\u7C7B\u578B
	 * @throws FTPClientException
	 * @throws IOException
	 */
	private static void setFileType(FTPClient ftpClient)
			throws FTPClientException, IOException {
		if (binaryTransfer) {
			ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
		} else {
			ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
		}
	}

	/**
	 * @description\u65AD\u5F00ftp\u8FDE\u63A5
	 * @throws FTPClientException
	 * @throws IOException
	 */
	public static void disconnect() throws FTPClientException, IOException {
		FTPClient ftpClient = getFTPClient();
		ftpClient.logout();
		if (ftpClient.isConnected()) {
			ftpClient.disconnect();
			ftpClient = null;
			ftpClientThreadLocal.set(ftpClient);
		}
	}

	/**
	 * @description \u6279\u91CF\u5220\u9664\u6240\u6709\u76EE\u5F55\u4E0B\u7684\u5BF9\u5E94\u7684\u6587\u4EF6
	 * @param delFiles
	 * @return
	 * @throws FTPClientException
	 * @throws IOException
	 */
	public static boolean deleteRemoteFiles(String[] delFiles)
			throws FTPClientException, IOException {
		 List<String> list=listNames();//\u83B7\u53D6\u6240\u6709\u7684\u6587\u4EF6\u540D
		 for(String filename:delFiles){
			 for(Iterator<String> it=list.iterator();it.hasNext();){
				 String filepath=it.next();
				 if(filepath.contains(filename)){//\u5982\u679C\u8BE5\u8DEF\u5F84\u5305\u542B\u8BE5\u6587\u4EF6\u540D\u5219\u5220\u9664
					boolean result= getFTPClient().deleteFile(filepath);
					if(!result){
						return result;
					}
				 }
			 }
		 }
		return true;
	}

	/**
	 * @description \u5217\u51FA\u8FDC\u7A0B\u9ED8\u8BA4\u76EE\u5F55\u4E0B\u6240\u6709\u7684\u6587\u4EF6
	 * @return \u8FDC\u7A0B\u9ED8\u8BA4\u76EE\u5F55\u4E0B\u6240\u6709\u6587\u4EF6\u540D\u7684\u5217\u8868\uFF0C\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u8005\u76EE\u5F55\u4E0B\u6CA1\u6709\u6587\u4EF6\u65F6\u8FD4\u56DE0\u957F\u5EA6\u7684\u6570\u7EC4
	 * @throws FTPClientException
	 * @throws IOException
	 */
	public static List<String> listNames() throws FTPClientException,
			IOException {
		return listNames(null);
	}

	public static List<String> listNames(String remotePath)
			throws FTPClientException, IOException {
		return listNames(remotePath, true);
	}

	/**
	 * @description\u5217\u51FA\u8FDC\u7A0B\u76EE\u5F55\u4E0B\u6240\u6709\u7684\u6587\u4EF6
	 * @param remotePath
	 *            \u8FDC\u7A0B\u76EE\u5F55\u540D
	 * @param autoClose
	 *            \u662F\u5426\u81EA\u52A8\u5173\u95ED\u5F53\u524D\u8FDE\u63A5
	 * @return \u8FDC\u7A0B\u76EE\u5F55\u4E0B\u6240\u6709\u6587\u4EF6\u540D\u7684\u5217\u8868\uFF0C\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u8005\u76EE\u5F55\u4E0B\u6CA1\u6709\u6587\u4EF6\u65F6\u8FD4\u56DE0\u957F\u5EA6\u7684\u6570\u7EC4
	 * @throws FTPClientException
	 * @throws IOException
	 */
	public static List<String> listNames(String remotePath,
			boolean containSubdirectory) throws FTPClientException, IOException {
		if (null == remotePath) {
			remotePath = "." + File.separator;
		}
		try {
			FTPFile[] files = getFTPClient().listFiles(remotePath);
			if (files.length < 3) {
				return listFileNames;
			}
			for (FTPFile file : files) {
				if (!file.getName().equals(".") && !file.getName().equals("..")) {
					if (file.isFile()) {// \u6587\u4EF6
						listFileNames
								.add("." + File.separator + file.getName());
					} else {// \u76EE\u5F55
						listNames2(
								remotePath + file.getName() + File.separator,
								containSubdirectory);
					}
				}
			}
		} catch (IOException e) {
			throw new FTPClientException("\u5217\u51FA\u8FDC\u7A0B\u76EE\u5F55\u4E0B\u6240\u6709\u7684\u6587\u4EF6\u65F6\u51FA\u73B0\u5F02\u5E38", e);
		}
		return listFileNames;
	}
     //listNames2\u9012\u5F52\u65B9\u6CD5
	private static void listNames2(String remotePath,
			boolean containSubdirectory) throws FTPClientException {
		try {
			FTPClient client = getFTPClient();
			client.changeWorkingDirectory(remotePath);
			FTPFile[] files = client.listFiles(remotePath);
			if (files.length < 3) {
				return;
			}
			for (FTPFile file : files) {
				if (!file.equals(".") && !file.equals("..")) {
					if (file.isFile()) {
						listFileNames.add(remotePath + file.getName());
					}
					if (file.isDirectory() && (!".".equals(file.getName()))
							&& (!"..".equals(file.getName()))) {
						String path = remotePath + file.getName()
								+ File.separator;
						listNames2(path, containSubdirectory);
					}
				}
			}
		} catch (IOException e) {
			throw new FTPClientException("\u5217\u51FA\u8FDC\u7A0B\u76EE\u5F55\u4E0B\u6240\u6709\u7684\u6587\u4EF6\u65F6\u51FA\u73B0\u5F02\u5E38", e);
		}
	}

	/**
	 * 
	 * @param remotePath
	 *            \u8FDC\u7A0B\u8DEF\u5F84
	 * @param fileName
	 *            \u8981\u4E0A\u4F20\u7684\u6587\u4EF6\u540D
	 * @param localInputStream
	 *            \u672C\u5730InputStream\u6D41
	 * @return
	 * @throws IOException
	 * @throws FTPClientException
	 */
	public static boolean uploadToRemote(String remotePath, String fileName,
			InputStream localInputStream) throws IOException,
			FTPClientException {
		remotePath=remotePath+File.separator;
		FTPClient client = getFTPClient();
		int reply;
		reply = client.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			client.disconnect();
		}
		client.makeDirectory(remotePath);//\u5728\u670D\u52A1\u7AEF\u5EFA\u7ACB\u8BE5\u6587\u4EF6\u5939
		client.changeWorkingDirectory(remotePath);
		boolean result = client.storeFile(remotePath+fileName, localInputStream);
		localInputStream.close();
		return result;
	}

	/**
	 * 
	 * @param remotePath
	 *            \u8FDC\u7A0B\u8DEF\u5F84
	 * @param localPath
	 *            \u672C\u5730\u8DEF\u5F84
	 * @return
	 * @throws IOException
	 * @throws FTPClientException
	 * @throws IOException
	 */
	public static boolean downloadToLocal(String remotePath, String localPath)
			throws IOException, FTPClientException, IOException {
		return downloadToLocal(remotePath, localPath, null);
	}

	/**
	 * 
	 * @param remotePath
	 *            \u8FDC\u7A0B\u8DEF\u5F84
	 * @param localPath
	 *            \u8981\u4E0B\u8F7D\u7684\u8DEF\u5F84
	 * @param fileNames
	 *            \u6240\u6709\u8981\u4E0B\u8F7D\u7684\u6587\u4EF6\u540D\u5B57
	 * @return
	 * @throws IOException
	 * @throws FTPClientException
	 * @throws IOException
	 */
	public static boolean downloadToLocal(String remotePath, String localPath,
			String[] fileNames) throws IOException, FTPClientException,
			IOException {
		remotePath=remotePath+File.separator;
		localPath=localPath+File.separator;
		FTPClient client = getFTPClient();
		client.changeWorkingDirectory(remotePath);
		FTPFile[] ftpList = client.listFiles(remotePath);
		boolean result = true;
		if (null == fileNames) {
			for (FTPFile f : ftpList) {
				if (f.getSize() > 0) {
					File file = new File(localPath);
					file.mkdirs();
					OutputStream out = new FileOutputStream(localPath + f.getName());
					result = client.retrieveFile(f.getName(), out); // \u4E0B\u8F7D
					out.close();
					if (!result) {
						break;
					}
				}
			}
		} else {
			for (String fileName : fileNames) {
				File file = new File(localPath);
				file.mkdirs();
				OutputStream out = new FileOutputStream(localPath
						+ File.separator + fileName);
				result = client.retrieveFile(fileName, out); // \u4E0B\u8F7D
				out.close();
				if (!result) {
					break;
				}
			}
		}
		return result;
	}

	/**
	 * @param client
	 * @param fileName
	 *            \u8FDC\u7A0B\u8DEF\u5F84\u540D
	 * @return
	 * @throws IOException
	 * @throws FTPClientException
	 */
	public static int getRemoteFileSize(String fileName) throws IOException,
			FTPClientException {
		FTPClient client = getFTPClient();
		int size = 0;
		FTPFile[] ftpList = client.listFiles();
		for (FTPFile f : ftpList) {
			if (f.getName().equalsIgnoreCase(fileName)) {
				size = (int) f.getSize();
			}
		}
		return size;
	}

	/**
	 * 
	 * @param filename
	 *            \u8981\u4E0B\u8F7D\u7684\u6587\u4EF6\u540D \u4ECE\u6574\u4E2A\u670D\u52A1\u5668\u4E2D\u67E5\u627E,\u53EF\u80FD\u627E\u5230\u591A\u4E2A\u76F8\u540C\u540D\u5B57\u7684\u6587\u4EF6,\u6309\u5728\u670D\u52A1\u7AEF\u7684\u8DEF\u5F84\u5728\u6307\u5B9A\u672C\u5730\u8DEF\u5F84\u4E0B\u521B\u5EFA\u60F3\u5BF9\u5E94\u7684\u8DEF\u5F84\u548C\u6587\u4EF6
	 * @param localPath
	 *            \u672C\u5730\u8DEF\u5F84
	 * @return
	 * @throws Exception 
	 */
	public static boolean downloadToLocal2(String filename, String localPath)
			throws Exception {
		 List<String> list=listNames();
		 OutputStream out;
		 try{
			 for(Iterator<String> it=list.iterator();it.hasNext();){
				 String filepath=it.next();
				 if(filepath.contains(filename)){
					 String remoteFilePath=filepath.substring(1, filepath.length());
					 File file=new File(localPath+remoteFilePath);
					 new File(file.getParent()).mkdirs();
					 out= new FileOutputStream(localPath+remoteFilePath);
					 getFTPClient().retrieveFile(filepath, out); // \u4E0B\u8F7D
					 out.close(); 
				 }
			 }
			 return true;
		 }catch (Exception e) {
			 return false;
		}
	}
	/**
	 * @description \u521B\u5EFA\u8FDC\u7A0B\u76EE\u5F55\u5141\u8BB8\u521B\u5EFA\u591A\u7EA7\u76EE\u5F55
	 * @param remoteDir \u8FDC\u7A0B\u76EE\u5F55
	 * @return
	 * @throws SocketException
	 * @throws IOException
	 * @throws FTPClientException
	 */
	public static boolean mkdirs(String remoteDir) throws SocketException, IOException, FTPClientException{
		String[] dirs=remoteDir.split("/");
		String remotePath=".";
		for(String dir:dirs){
			if(!dir.equals(".")&&null!=dir){
				remotePath=remotePath+File.separator+dir+File.separator;
				boolean result=getFTPClient().makeDirectory(remotePath);
				if(!result){
					return result;
				}
			}
		}
		return true;
	}
}

FTPClientUtil FTPclient工具

标签:code   name   array   hang   contains   ftps   connected   iterator   param   

原文地址:http://www.cnblogs.com/gccbuaa/p/6871678.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!