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. String.Format数字格式化输出 {0:N2} {0:D2} {0:C2

    //格式为sring输出 //   Label1.Text = string.Format("asdfadsf{0}adsfasdf",a); //   Label2.Text = ...

  2. DataGridView 分页显示

    DataGridView 分页显示函数 1.获取当前页的子数据表函数 public static DataTable GetPagedTable(DataTable dt, int PageIndex ...

  3. C#委托的异步调用1

    本文将主要通过“同步调用”.“异步调用”.“异步回调”三个示例来讲解在用委托执行同一个“加法类”的时候的的区别和利弊. 首先,通过代码定义一个委托和下面三个示例将要调用的方法: /*添加的命名空间 u ...

  4. 【Sqlserver】修改数据库表中的数据:对缺失的数据根据已有的数据进行修补

    1 --查询时间范围内的数据 select * from dbo.point where wtime >'2014-05-01 23:59:59' and wtime< '2014-05- ...

  5. 一款js控制背景图片平铺

    背景图片的平铺方法有很多种,纯色背景,渐变背景,图片背景,今天讲的是移动端的图片背景~~~~ <style> html,body{;;} .body{background: url(ima ...

  6. css中单位px,em,rem的区别

    1,px像素(Pixel).相对长度单位.像素px是相对于显示器屏幕分辨率而言的. 2,em是相对长度单位.相对于当前对象内文本的字体尺寸.如当前对行内文本的字体尺寸未被人为设置,则相对于浏览器的默认 ...

  7. webpack减少打包后文件体积的几种方法

    webpack 把我们所有的文件都打包成一个 JS 文件,这样即使你是小项目,打包后的文件也会非常大.下面就来讲下如何从多个方面进行优化. 去除不必要的插件 刚开始用 webpack 的时候,开发环境 ...

  8. uniquery 在win2008 下hold的问题。

    TmpQry.ReadOnly := True; 加上这句解决,原因未知!

  9. 一个基于python的即时通信程序

    5月17日更新: 广播信息.用户列表.信息确认列表以及通信信息,从原来的用字符串存储改为使用字典来存储,使代码更清晰,更容易扩展,具体更改的格式如下: 广播信息(上线): { 'status': 信息 ...

  10. Android开发中Eclipse里的智能提示设置

    今天开始学习一下Android开发,直接在Android Developers下载的一个开发工具包,然后再下了一个JDK,配置完环境变量等一系列的工作后环境就搭建好了,在新建好第一个Android项目 ...