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.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger; /**
* 提供上传图片文件, 文件夹
* @author MYMOON
*
*/
public class UpFTPClient {
private static Logger logger = Logger.getLogger(UpFTPClient.class.getName()); private ThreadLocal<FTPClient> ftpClientThreadLocal = new ThreadLocal<FTPClient>(); private String encoding = "UTF-8";
private int clientTimeout = 1000 * 30;
private boolean binaryTransfer = true; private String host;
private int port;
private String username;
private String password; private FTPClient getFTPClient() {
if (ftpClientThreadLocal.get() != null && ftpClientThreadLocal.get().isConnected()) {
return ftpClientThreadLocal.get();
} else {
FTPClient ftpClient = new FTPClient(); // 构造一个FtpClient实例
ftpClient.setControlEncoding(encoding); // 设置字符集 try {
connect(ftpClient); // 连接到ftp服务器
setFileType(ftpClient); //设置文件传输类型
ftpClient.setSoTimeout(clientTimeout);
} catch (Exception e) { e.printStackTrace();
} ftpClientThreadLocal.set(ftpClient);
return ftpClient;
}
} /**
* 连接到ftp服务器
*/
private boolean connect(FTPClient ftpClient) throws Exception {
try {
ftpClient.connect(host, port); // 连接后检测返回码来校验连接是否成功
int reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) {
//登陆到ftp服务器
if (ftpClient.login(username, password)) {
return true;
}
} else {
ftpClient.disconnect();
throw new Exception("FTP server refused connection.");
}
} catch (IOException e) {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect(); //断开连接
} catch (IOException e1) {
throw new Exception("Could not disconnect from server.", e1);
} }
throw new Exception("Could not connect to server.", e);
}
return false;
} /**
* 断开ftp连接
*/
public void disconnect() throws Exception {
try {
FTPClient ftpClient = getFTPClient();
ftpClient.logout();
if (ftpClient.isConnected()) {
ftpClient.disconnect();
ftpClient = null;
}
} catch (IOException e) {
throw new Exception("Could not disconnect from server.", e);
}
} /**
* 设置文件传输类型
*
* @throws FTPClientException
* @throws IOException
*/
private void setFileType(FTPClient ftpClient) throws Exception {
try {
if (binaryTransfer) {
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
} else {
ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);
}
} catch (IOException e) {
throw new Exception("Could not to set file type.", e);
}
} //---------------------------------------------------------------------
// public method
//--------------------------------------------------------------------- /**
* 上传一个本地文件到远程指定文件
*
* @param remoteDir 远程文件名(包括完整路径)
* @param localAbsoluteFile 本地文件名(包括完整路径)
* @param autoClose 是否自动关闭当前连接
* @return 成功时,返回true,失败返回false
* @throws FTPClientException
*/
public boolean uploadFile(String localAbsoluteFile, String remoteDir, String filename) throws Exception {
InputStream input = null;
try {
getFTPClient().makeDirectory(remoteDir);
// 处理传输
input = new FileInputStream(localAbsoluteFile);
boolean rs = getFTPClient().storeFile(remoteDir+filename, input);
return rs;
} catch (FileNotFoundException e) {
throw new Exception("local file not found.", e);
} catch (IOException e) {
throw new Exception("Could not put file to server.", e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception e) {
throw new Exception("Couldn't close FileInputStream.", e);
}
}
} /***
* @上传文件夹
* @param localDirectory 当地文件夹
* @param remoteDirectoryPath Ftp 服务器路径 以目录"/"结束
* */
public boolean uploadDirectory(String localDirectory, String remoteDirectoryPath) {
File src = new File(localDirectory);
try {
getFTPClient().makeDirectory(remoteDirectoryPath); } catch (IOException e) {
e.printStackTrace();
logger.info(remoteDirectoryPath + "目录创建失败");
} File[] allFile = src.listFiles();
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
String srcName = allFile[currentFile].getPath().toString();
uploadFile(new File(srcName), remoteDirectoryPath);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
// 递归
uploadDirectory(allFile[currentFile].getPath().toString(), remoteDirectoryPath);
}
}
return true;
} /***
* 上传Ftp文件 配合文件夹上传
* @param localFile 当地文件
* @param romotUpLoadePath上传服务器路径
* - 应该以/结束
* */
private boolean uploadFile(File localFile, String romotUpLoadePath) {
BufferedInputStream inStream = null;
boolean success = false;
try {
getFTPClient().changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
inStream = new BufferedInputStream(new FileInputStream(localFile));
logger.info(localFile.getName() + "开始上传.....");
success = getFTPClient().storeFile(localFile.getName(), inStream);
if (success == true) {
logger.info(localFile.getName() + "上传成功");
return success;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(localFile + "未找到");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
} public String[] listNames(String remotePath, boolean autoClose) throws Exception{
try {
String[] listNames = getFTPClient().listNames(remotePath);
return listNames;
} catch (IOException e) {
throw new Exception("列出远程目录下所有的文件时出现异常", e);
} finally {
if (autoClose) {
disconnect(); //关闭链接
}
}
} public String getEncoding() {
return encoding;
} public void setEncoding(String encoding) {
this.encoding = encoding;
} public int getClientTimeout() {
return clientTimeout;
} public void setClientTimeout(int clientTimeout) {
this.clientTimeout = clientTimeout;
} public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} 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 boolean isBinaryTransfer() {
return binaryTransfer;
} public void setBinaryTransfer(boolean binaryTransfer) {
this.binaryTransfer = binaryTransfer;
} /**
* 目标路径 按年月存图片: 201405
* 限时打折 /scenery/ ticket, hotel, catering
* 浪漫之游 /discount/
*
* @param args
*/
public static void main(String[] args) { UpFTPClient ftp = new UpFTPClient();
ftp.setHost("192.168.0.181");
ftp.setPort(21);
ftp.setUsername("ftpgt");
ftp.setPassword("ftpgt"); try {
// 上传整个目录
ftp.uploadDirectory("F:/tmp/njff/", "/noff/"); // 上传单个文件
boolean rs = ftp.uploadFile("F:/tmp/njff/02.jpg", "/201301/", "02.jpg");
System.out.println(">>>>>>> " + rs); // 列表
String[] listNames = ftp.listNames("/", true);
System.out.println(Arrays.asList(listNames)); ftp.disconnect(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }

FTPClient 工具类的更多相关文章

  1. FTPClient工具类

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

  2. FTP工具类开发

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

  3. FTP上传-封装工具类

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

  4. java中常用的工具类(二)

    下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil           Java   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  5. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...

  6. ftp上传或下载文件工具类

    FtpTransferUtil.java工具类,向ftp上传或下载文件: package utils; import java.io.File; import java.io.FileOutputSt ...

  7. Java操作FTP工具类(实例详解)

    这里使用Apache的FTP jar 包 没有使用Java自带的FTPjar包  工具类 package com.zit.ftp; import java.io.File; import java.i ...

  8. ftp上传下载工具类

    package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...

  9. FTPUtil工具类

    package com.xxx.common.util; import java.io.File; import java.io.FileOutputStream; import java.io.IO ...

随机推荐

  1. 使用WebJar管理css、JavaScript文件

    Web前端使用了越来越多的JS或CSS,如jQuery, Backbone.js 和Bootstrap.一般情况下,我们是将这些Web资源拷贝到Java的目录下,通过手工进行管理,这种通方式容易导致文 ...

  2. TweenMax动画库学习(一)

    目录            TweenMax动画库学习(一)            TweenMax动画库学习(二)            TweenMax动画库学习(三)            Tw ...

  3. 【解惑】深入jar包:从jar包中读取资源文件

    [解惑]深入jar包:从jar包中读取资源文件 http://hxraid.iteye.com/blog/483115 TransferData组件的spring配置文件路径:/D:/develop/ ...

  4. 一款jquery写出来的tab切换

    当时做这个的时候,当前状态是不规则的,li对应的有3块内容,分别设定不同背景图片,只显示当前的一个背景,鼠标移上去的时候其余2个用background-position: -1000px 0px;来隐 ...

  5. MongoDB的安全性

    上篇文章介绍Mongo启动了,一般数据库启动,下面的操作就是登录数据库了,之前测试数据库是否正常安装的时候也登录过数据库,现在回想一下,好像连用户名和密码都没有输入,找几篇帖子来探究下Mongodb的 ...

  6. background之你不知道的background-position

    这是一个有趣的话题 其实我并不确切的平时大家是怎么去应用或者玩转一个属性,一个值.我能肯定的是这些东西都有不少的可玩性. 我今天要聊的 background-position 应该已经被大家玩得色彩斑 ...

  7. 【WPF】Application应用程序启动

    wpf应用程序在启动的时候会自动创建Main函数并调用Application实例的run(),从而启动Application进程.Main函数在一个App.g.cs文件中,App.g.cs文件的位置在 ...

  8. 元类metaClass

    metaClass 实现动态改变对象的能力,这点特别像python(metaClass),Python中类(不是元类)的概念借鉴于Smalltalk groovy demo: class Person ...

  9. EXTJS 3.0 资料 控件之 FormPanel 插入button用法

    最近发现项目中FormPanel 里面需要 增加 button,的模块比较多,具体代码如下: var eastPanelForm_Dele = new Ext.form.FormPanel({ id: ...

  10. SharpDeveloeper开发ASP.NET MVC汗流浃背

    今天好不容易休息了一天,上网狂了一圈,突然想起了以前的一个轻量级的开发工具"SharpDeveloper",于是就下载试着来开发一下ASP.NET,但是老魏没有想到的是,虽然官方提 ...