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. js中 在数组中删除重复的元素(自保留一个)

    例如:var student = [‘qiang’,’ming’,’tao’,’li’,’liang’,’you’,’qiang’,’tao’]; 第一种思路是:遍历要删除的数组arr, 把元素分别放 ...

  2. 简单使用packetbeat

    简单使用packetbeat 标签:packetbeat elasticsearch 版权声明:原创作品,谢绝转载!否则将追究法律责任. 在前面两篇文章中记录了使用logstash来收集mysql的慢 ...

  3. BootStrap中Affix控件的使用方法及如何保持布局的美观

    Affix是BootStrap中的一个很有用的控件,他能够监视浏览器的滚动条的位置并让你的导航始终都在页面的可视区域.一开始的时候,导航在页面中是普通的流式布局,占有文档中固定的位置,当页面滚动的时候 ...

  4. Js popup position which right under target item

    <div style="margin-left:600px;"> <div id="Span1" style="color:#eee ...

  5. [Linux] Linux学习笔记(5)-文件与目录管理

    1.Linux目录结构为树状结构,最顶层的目录为跟目录"/",其它目录通过挂载可以将它添加到目录树中,通过解除挂载移除它们. 2.绝对路径与相对路径 绝对路径写法:由根目录&quo ...

  6. php curl基本操作

    如何使用cURL的基本方法?首先,修改php.ini文件的设置,找到php_curl.dll,取消下在的注释extension=php_curl.dll,因为php默认是不开启cURL的. cURL是 ...

  7. Dapper.ColumnMapper 的使用

    using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; usin ...

  8. C# 判断点是否在多边形内

    /// <summary>/// 判断点是否在多边形内/// </summary>/// <param name="pnt">点</par ...

  9. 《C和指针》 读书笔记 -- 第9章 字符串、字符和字节

    1.字符串以NUL结尾,但字符串长度不包括NUl字节. 2.复制字符串 char *strcpy(char *dst,char const *src); 3.连接字符串 char *strcat(ch ...

  10. Android UI效果实现——滑动模糊渐变效果实现

    前言: 大家应该都看到过iOS7解锁屏幕的滑动模糊渐变效果,好了,现在可以把手纸收起来了,今天黄老师就给大家讲一下如何在Android平台上 实现类似的滑动模糊渐变效果,其实方式远比你想像的简单. 目 ...