FTPClientUtil FTPclient工具

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;
	}
}
时间: 2024-07-28 15:28:09

FTPClientUtil FTPclient工具的相关文章

FTPClient 工具类

package com.photoann.core.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import org

淘淘商城第三天笔记

第三天笔记 1 课程计划 后台管理商品的添加功能 1.商品分类选择 2.上传图片 3.富文本编辑器(kindEditor) 4.实现商品的添加 5.课后作业(商品的修改.删除) 2 商品添加功能说明 3 类目选择 3.1 需求 点击类目选择按钮弹出类目选择窗口,窗口中是一个树形视图.分级展示商品分类.当选择商品分类的叶子节点后,关闭窗口并将选中的商品分类的名称显示到网页上. 1.初始化tree的url: /item/cat/list 2.请求的参数 Id(当前节点的id,根据此id查询子节点)

引入模板模式重构FtpClientUtil

在<ftp上传与下载>文章中,封装一个Ftp上传下载的工具类,主要代码如下: 上传: /**上传文件 * @param remoteFileName 远程文件名称 * @param locaFileName 本地文件名称 */ public void upload(String remoteFileName,String locaFileName){ FTPClient ftp=null; try { ftp = new FTPClient(); ftp.addProtocolCommandL

简单主机批量管理工具

题目:简单主机批量管理工具 需求: 主机分组 登录后显示主机分组,选择分组后查看主机列表 可批量执行命令.发送文件,结果实时返回 主机用户名密码可以不同 流程图: 说明: ### 作者介绍: * author:lzl ### 博客地址: * http://www.cnblogs.com/lianzhilei/p/5881434.html ### 功能实现 题目:简单主机批量管理工具 需求: 主机分组 登录后显示主机分组,选择分组后查看主机列表 可批量执行命令.发送文件,结果实时返回 主机用户名密

图片上传功能的几个工具类的介绍

(1)FTP上传文件的工具类: package com.taotao.common.utils; import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream

java中常用的工具类(二)

下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

java中常用的工具类

一.String工具类 package com.itjh.javaUtil; import java.util.ArrayList; import java.util.List; /** * * String工具类. <br> * * @author 宋立君 * @date 2014年06月24日 */ public class StringUtil { private static final int INDEX_NOT_FOUND = -1; private static final St

用edtftpj实现Java FTP客户端工具

edtftpj是一个java FTP工具包,使用非常方便,感觉比Apache的好用,但Apache更灵活.edtftpj有多种版本,分别是java..net和js版本.对于Java版的有一个免费版本.我用的就是免费版本.其余的均为商业版本. 为了开发,先下载免费版本的开发包. 主  页:http://www.enterprisedt.com/ 工具包:http://www.enterprisedt.com/products/edtftpj/download/edtftpj.zip 目前我用的是2

ftp工具类

package com.ttg.utils.common; //~--- non-JDK imports -------------------------------------------------------- import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPClientConfig; import org.apache.commons.net.ftp.FTPFile; i