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工具的更多相关文章

  1. FTPClient 工具类

    package com.photoann.core.util; import java.io.BufferedInputStream; import java.io.File; import java ...

  2. 纪念使用FTPClient工具所遇到的

    我所使用的是org.apache.commons.net.ftp.FTPClient.  查了资料还有其余几个FTPClient,其余的先不展开. 1.ftpClient.changeWorkingD ...

  3. FTPClient工具类

    package com.vcredit.ddcash.server.commons.net; import com.vcredit.ddcash.server.commons.model.FtpPar ...

  4. FTP上传心得

    最近出了一个问题就是在本地上传FTP没有一点问题 可是部署到服务器上.上传的时候总是false.解决办法 ftp.enterLocalPassiveMode();boolean storeFile = ...

  5. 【大话QT之十六】使用ctkPluginFramework插件系统构建项目实战

    "使用ctkPluginFramework插件系统构建项目实战",这篇文章是写博客以来最纠结的一篇文章. 倒不是由于技术都多么困难,而是想去描写叙述一个项目架构採用ctkPlugi ...

  6. FtpServer穿透内网访问配置踩笔记

    FtpServer穿透内网访问配置踩笔记 引言 FtpServer是服务器文件远程管理常用方式. 以前在局域网配置Ftp服务器以及使用公网上的Ftp服务均未碰到问题,固未对Ftp传输进行深入了解. 然 ...

  7. Java FtpClient 实现文件上传服务

    一.Ubuntu 安装 Vsftpd 服务 1.安装 sudo apt-get install vsftpd 2.添加用户(uftp) sudo useradd -d /home/uftp -s /b ...

  8. FTP工具类开发

    正所谓工欲善其事必先利其器,熟悉了下一套流程,以此铭记. 1.FTP服务搭建 由于本人使用wondiow系统,所以针对window的童鞋们可以查看.至于windowX这里配置类似,所以不要纠结于win ...

  9. FTP上传-封装工具类

    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...

随机推荐

  1. 树莓派GPIO点亮第一个led

    代码如下: 注意:::::此时的GPIO口为18编号口而非GPIO18 import RPi.GPIO as GPIO //引入函数库 import time RPi.GPIO.setmode(GPI ...

  2. SugarCRM安装过程——PHP文件上传限制问题

    找到D:\xampp\php目录下,php文件中的php.ini文件,用写字板打开: 1.查找post_max_size,指通过表单POST给PHP的所能接收的最大值,包括表单里的所有值,默认为8M, ...

  3. 上传一个npm包

    1.先创建一个npm账号 https://www.npmjs.com/signup 2.在cmd里输入命令进入项目文件夹 3.使用npm init 命令创建一个package.json(确保nodej ...

  4. tensorFlow资源

    1,[莫烦]Tensorflow tutorials (Eng Sub) 神经网络 http://www.bilibili.com/video/av10118932/index_35.html#pag ...

  5. self和super的区别

    (1)self调用自己方法,super调用父类方法 (2)self是类,super是预编译指令 (3)[self class]和[super class]输出是一样的 ①当使用 self 调用方法时, ...

  6. firefox + pentadactyl 实现纯绿色高效易扩展浏览器(同时实现修改默认状态栏样式)

    这几天开始使用firefox+pentadactyl来搭建一个开源.可扩展.完全绿化的浏览器环境,以便随身带着使用,其中firefox的使用了24.0的长期支持版, 这边版本稳定, 快速, 兼容性好, ...

  7. Zynq7000系列之芯片引脚功能综述

    很多人做了很久的FPGA,知道怎么去给信号分配引脚,却对这些引脚的功能及其资源限制知之甚少:在第一章里对Zynq7000系列的系统框架进行了分析和论述,对Zynq7000系列的基本资源和概念有了大致的 ...

  8. 获取WebBrowser全cookie 和 httpWebRequest 异步获取页面数据

    获取WebBrowser全cookie [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true) ...

  9. java虚拟机(六)--垃圾收集器和内存分配策略

    目前没有完美的收集器,不同的厂商.版本的虚拟机提供的垃圾收集器会有很大的差别,用户根据自己应用特点和要求组合出各个年代所使用 的收集器.基于jdk1.7Update14之后的虚拟机. HotSpot的 ...

  10. Linux安装redis并且连接内网的redis

    1.安装redis步骤 1.首先准备工作  [root@10-100-14-130 ~]# yum install gcc-c++   yum install wget 2.推荐进入到linux路径/ ...