设为首页 收藏本站
查看: 875|回复: 0

[经验分享] Java FTP客户端代码(二)

[复制链接]

尚未签到

发表于 2016-6-9 09:32:06 | 显示全部楼层 |阅读模式
该版本主要增加了以下特性:
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);
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-228089-1-1.html 上篇帖子: FTP协议的命令的使用(转) 下篇帖子: 四十四、Qt网络(四)FTP(二)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表