Java FTPClient代码(二)支持多线程与连接复用

2024-01-05 18:38

本文主要是介绍Java FTPClient代码(二)支持多线程与连接复用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

该版本主要增加了以下特性:
1、对多线程并发的支持
2、连接复用


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;/*** FTP客户端* * @author summersun_ym* @version $Id: FTPClientTemplate.java 2010-11-22 上午12:54:47 $*/
public class FTPClientTemplate {//---------------------------------------------------------------------// Instance data//---------------------------------------------------------------------/** logger */protected final Logger         log                  = Logger.getLogger(getClass());private ThreadLocal<FTPClient> ftpClientThreadLocal = new ThreadLocal<FTPClient>();private String                 host;private int                    port;private String                 username;private String                 password;private boolean                binaryTransfer       = true;private boolean                passiveMode          = true;private String                 encoding             = "UTF-8";private int                    clientTimeout        = 1000 * 30;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;}public boolean isPassiveMode() {return passiveMode;}public void setPassiveMode(boolean passiveMode) {this.passiveMode = passiveMode;}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;}//---------------------------------------------------------------------// private method//---------------------------------------------------------------------/*** 返回一个FTPClient实例* * @throws FTPClientException*/private FTPClient getFTPClient() throws FTPClientException {if (ftpClientThreadLocal.get() != null && ftpClientThreadLocal.get().isConnected()) {return ftpClientThreadLocal.get();} else {FTPClient ftpClient = new FTPClient(); //构造一个FtpClient实例ftpClient.setControlEncoding(encoding); //设置字符集connect(ftpClient); //连接到ftp服务器//设置为passive模式if (passiveMode) {ftpClient.enterLocalPassiveMode();}setFileType(ftpClient); //设置文件传输类型try {ftpClient.setSoTimeout(clientTimeout);} catch (SocketException e) {throw new FTPClientException("Set timeout error.", e);}ftpClientThreadLocal.set(ftpClient);return ftpClient;}}/*** 设置文件传输类型* * @throws FTPClientException* @throws IOException*/private void setFileType(FTPClient ftpClient) throws FTPClientException {try {if (binaryTransfer) {ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);} else {ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);}} catch (IOException e) {throw new FTPClientException("Could not to set file type.", e);}}/*** 连接到ftp服务器* * @param ftpClient* @return 连接成功返回true,否则返回false* @throws FTPClientException*/private boolean connect(FTPClient ftpClient) throws FTPClientException {try {ftpClient.connect(host, port);// 连接后检测返回码来校验连接是否成功int reply = ftpClient.getReplyCode();if (FTPReply.isPositiveCompletion(reply)) {//登陆到ftp服务器if (ftpClient.login(username, password)) {setFileType(ftpClient);return true;}} else {ftpClient.disconnect();throw new FTPClientException("FTP server refused connection.");}} catch (IOException e) {if (ftpClient.isConnected()) {try {ftpClient.disconnect(); //断开连接} catch (IOException e1) {throw new FTPClientException("Could not disconnect from server.", e1);}}throw new FTPClientException("Could not connect to server.", e);}return false;}//---------------------------------------------------------------------// public method//---------------------------------------------------------------------/*** 断开ftp连接* * @throws FTPClientException*/public void disconnect() throws FTPClientException {try {FTPClient ftpClient = getFTPClient();ftpClient.logout();if (ftpClient.isConnected()) {ftpClient.disconnect();ftpClient = null;}} catch (IOException e) {throw new FTPClientException("Could not disconnect from server.", e);}}public boolean mkdir(String pathname) throws FTPClientException {return mkdir(pathname, null);}/*** 在ftp服务器端创建目录(不支持一次创建多级目录)* * 该方法执行完后将自动关闭当前连接* * @param pathname* @return* @throws FTPClientException*/public boolean mkdir(String pathname, String workingDirectory) throws FTPClientException {return mkdir(pathname, workingDirectory, true);}/*** 在ftp服务器端创建目录(不支持一次创建多级目录)* * @param pathname* @param autoClose 是否自动关闭当前连接* @return* @throws FTPClientException*/public boolean mkdir(String pathname, String workingDirectory, boolean autoClose) throws FTPClientException {try {getFTPClient().changeWorkingDirectory(workingDirectory);return getFTPClient().makeDirectory(pathname);} catch (IOException e) {throw new FTPClientException("Could not mkdir.", e);} finally {if (autoClose) {disconnect(); //断开连接}}}/*** 上传一个本地文件到远程指定文件* * @param remoteAbsoluteFile 远程文件名(包括完整路径)* @param localAbsoluteFile 本地文件名(包括完整路径)* @return 成功时,返回true,失败返回false* @throws FTPClientException*/public boolean put(String remoteAbsoluteFile, String localAbsoluteFile) throws FTPClientException {return put(remoteAbsoluteFile, localAbsoluteFile, true);}/*** 上传一个本地文件到远程指定文件* * @param remoteAbsoluteFile 远程文件名(包括完整路径)* @param localAbsoluteFile 本地文件名(包括完整路径)* @param autoClose 是否自动关闭当前连接* @return 成功时,返回true,失败返回false* @throws FTPClientException*/public boolean put(String remoteAbsoluteFile, String localAbsoluteFile, boolean autoClose) throws FTPClientException {InputStream input = null;try {// 处理传输input = new FileInputStream(localAbsoluteFile);getFTPClient().storeFile(remoteAbsoluteFile, input);log.debug("put " + localAbsoluteFile);return true;} catch (FileNotFoundException e) {throw new FTPClientException("local file not found.", e);} catch (IOException e) {throw new FTPClientException("Could not put file to server.", e);} finally {try {if (input != null) {input.close();}} catch (Exception e) {throw new FTPClientException("Couldn't close FileInputStream.", e);}if (autoClose) {disconnect(); //断开连接}}}/*** 下载一个远程文件到本地的指定文件* * @param remoteAbsoluteFile 远程文件名(包括完整路径)* @param localAbsoluteFile 本地文件名(包括完整路径)* @return 成功时,返回true,失败返回false* @throws FTPClientException*/public boolean get(String remoteAbsoluteFile, String localAbsoluteFile) throws FTPClientException {return get(remoteAbsoluteFile, localAbsoluteFile, true);}/*** 下载一个远程文件到本地的指定文件* * @param remoteAbsoluteFile 远程文件名(包括完整路径)* @param localAbsoluteFile 本地文件名(包括完整路径)* @param autoClose 是否自动关闭当前连接* * @return 成功时,返回true,失败返回false* @throws FTPClientException*/public boolean get(String remoteAbsoluteFile, String localAbsoluteFile, boolean autoClose) throws FTPClientException {OutputStream output = null;try {output = new FileOutputStream(localAbsoluteFile);return get(remoteAbsoluteFile, output, autoClose);} catch (FileNotFoundException e) {throw new FTPClientException("local file not found.", e);} finally {try {if (output != null) {output.close();}} catch (IOException e) {throw new FTPClientException("Couldn't close FileOutputStream.", e);}}}/*** 下载一个远程文件到指定的流 处理完后记得关闭流* * @param remoteAbsoluteFile* @param output* @return* @throws FTPClientException*/public boolean get(String remoteAbsoluteFile, OutputStream output) throws FTPClientException {return get(remoteAbsoluteFile, output, true);}/*** 下载一个远程文件到指定的流 处理完后记得关闭流* * @param remoteAbsoluteFile* @param output* @param delFile* @return* @throws FTPClientException*/public boolean get(String remoteAbsoluteFile, OutputStream output, boolean autoClose) throws FTPClientException {try {FTPClient ftpClient = getFTPClient();// 处理传输return ftpClient.retrieveFile(remoteAbsoluteFile, output);} catch (IOException e) {throw new FTPClientException("Couldn't get file from server.", e);} finally {if (autoClose) {disconnect(); //关闭链接}}}/*** 从ftp服务器上删除一个文件* 该方法将自动关闭当前连接* * @param delFile* @return* @throws FTPClientException*/public boolean delete(String delFile) throws FTPClientException {return delete(delFile, true);}/*** 从ftp服务器上删除一个文件* * @param delFile* @param autoClose 是否自动关闭当前连接* * @return* @throws FTPClientException*/public boolean delete(String delFile, boolean autoClose) throws FTPClientException {try {getFTPClient().deleteFile(delFile);return true;} catch (IOException e) {throw new FTPClientException("Couldn't delete file from server.", e);} finally {if (autoClose) {disconnect(); //关闭链接}}}/*** 批量删除* 该方法将自动关闭当前连接* * @param delFiles* @return* @throws FTPClientException*/public boolean delete(String[] delFiles) throws FTPClientException {return delete(delFiles, true);}/*** 批量删除* * @param delFiles* @param autoClose 是否自动关闭当前连接* * @return* @throws FTPClientException*/public boolean delete(String[] delFiles, boolean autoClose) throws FTPClientException {try {FTPClient ftpClient = getFTPClient();for (String s : delFiles) {ftpClient.deleteFile(s);}return true;} catch (IOException e) {throw new FTPClientException("Couldn't delete file from server.", e);} finally {if (autoClose) {disconnect(); //关闭链接}}}/*** 列出远程默认目录下所有的文件* * @return 远程默认目录下所有文件名的列表,目录不存在或者目录下没有文件时返回0长度的数组* @throws FTPClientException*/public String[] listNames() throws FTPClientException {return listNames(null, true);}public String[] listNames(boolean autoClose) throws FTPClientException {return listNames(null, autoClose);}/*** 列出远程目录下所有的文件* * @param remotePath 远程目录名* @param autoClose 是否自动关闭当前连接* * @return 远程目录下所有文件名的列表,目录不存在或者目录下没有文件时返回0长度的数组* @throws FTPClientException*/public String[] listNames(String remotePath, boolean autoClose) throws FTPClientException {try {String[] listNames = getFTPClient().listNames(remotePath);return listNames;} catch (IOException e) {throw new FTPClientException("列出远程目录下所有的文件时出现异常", e);} finally {if (autoClose) {disconnect(); //关闭链接}}}public static void main(String[] args) throws FTPClientException, InterruptedException {FTPClientTemplate ftp = new FTPClientTemplate();ftp.setHost("localhost");ftp.setPort(2121);ftp.setUsername("admin");ftp.setPassword("admin");ftp.setBinaryTransfer(false);ftp.setPassiveMode(false);ftp.setEncoding("utf-8");//boolean ret = ftp.put("/group/tbdev/query/user-upload/12345678910.txt", "D:/099_temp/query/12345.txt");//System.out.println(ret);ftp.mkdir("asd", "user-upload");//ftp.disconnect();//ftp.mkdir("user-upload1");//ftp.disconnect();//String[] aa = {"/group/tbdev/query/user-upload/123.txt", "/group/tbdev/query/user-upload/SMTrace.txt"};//ftp.delete(aa);}
}复用

这篇关于Java FTPClient代码(二)支持多线程与连接复用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/573778

相关文章

Java计算经纬度距离的示例代码

《Java计算经纬度距离的示例代码》在Java中计算两个经纬度之间的距离,可以使用多种方法(代码示例均返回米为单位),文中整理了常用的5种方法,感兴趣的小伙伴可以了解一下... 目录1. Haversine公式(中等精度,推荐通用场景)2. 球面余弦定理(简单但精度较低)3. Vincenty公式(高精度,

QT6中绘制UI的两种方法详解与示例代码

《QT6中绘制UI的两种方法详解与示例代码》Qt6提供了两种主要的UI绘制技术:​​QML(QtMeta-ObjectLanguage)​​和​​C++Widgets​​,这两种技术各有优势,适用于不... 目录一、QML 技术详解1.1 QML 简介1.2 QML 的核心概念1.3 QML 示例:简单按钮

使用Java将实体类转换为JSON并输出到控制台的完整过程

《使用Java将实体类转换为JSON并输出到控制台的完整过程》在软件开发的过程中,Java是一种广泛使用的编程语言,而在众多应用中,数据的传输和存储经常需要使用JSON格式,用Java将实体类转换为J... 在软件开发的过程中,Java是一种广泛使用的编程语言,而在众多应用中,数据的传输和存储经常需要使用j

Java实现视频格式转换的完整指南

《Java实现视频格式转换的完整指南》在Java中实现视频格式的转换,通常需要借助第三方工具或库,因为视频的编解码操作复杂且性能需求较高,以下是实现视频格式转换的常用方法和步骤,需要的朋友可以参考下... 目录核心思路方法一:通过调用 FFmpeg 命令步骤示例代码说明优点方法二:使用 Jaffree(FF

Java实现图片淡入淡出效果

《Java实现图片淡入淡出效果》在现代图形用户界面和游戏开发中,**图片淡入淡出(FadeIn/Out)**是一种常见且实用的视觉过渡效果,它可以用于启动画面、场景切换、轮播图、提示框弹出等场景,通过... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细

Java如何用乘号来重复字符串的功能

《Java如何用乘号来重复字符串的功能》:本文主要介绍Java使用乘号来重复字符串的功能,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java乘号来重复字符串的功能1、利用循环2、使用StringBuilder3、采用 Java 11 引入的String.rep

SpringBoot中HTTP连接池的配置与优化

《SpringBoot中HTTP连接池的配置与优化》这篇文章主要为大家详细介绍了SpringBoot中HTTP连接池的配置与优化的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录一、HTTP连接池的核心价值二、Spring Boot集成方案方案1:Apache HttpCl

Spring Boot项目打包和运行的操作方法

《SpringBoot项目打包和运行的操作方法》SpringBoot应用内嵌了Web服务器,所以基于SpringBoot开发的web应用也可以独立运行,无须部署到其他Web服务器中,下面以打包dem... 目录一、打包为JAR包并运行1.打包为可执行的 JAR 包2.运行 JAR 包二、打包为WAR包并运行

Java进行日期解析与格式化的实现代码

《Java进行日期解析与格式化的实现代码》使用Java搭配ApacheCommonsLang3和Natty库,可以实现灵活高效的日期解析与格式化,本文将通过相关示例为大家讲讲具体的实践操作,需要的可以... 目录一、背景二、依赖介绍1. Apache Commons Lang32. Natty三、核心实现代

Spring Boot 常用注解整理(最全收藏版)

《SpringBoot常用注解整理(最全收藏版)》本文系统整理了常用的Spring/SpringBoot注解,按照功能分类进行介绍,每个注解都会涵盖其含义、提供来源、应用场景以及代码示例,帮助开发... 目录Spring & Spring Boot 常用注解整理一、Spring Boot 核心注解二、Spr