[Java] 使用 Apache的 Commons-net库 实现FTP操作
因为最近工作中需要用到FTP操作,而手上又没有现成的FTP代码。就去网上找了一下,发现大家都使用Apache的 Commons-net库中的FTPClient。
但是,感觉用起来不太方便。又在网上找到了很多封装过的。觉得也不是很好用。于是就自己写了一个。网上大多是例子都是直接对文件进行操作,而我更需要的是读到内存,或者从内存上写。并且有很多实用单例模式,但是我觉得如果调用比较多的话,可能会出现问题。
package com.best.oasis.util.helper; /**
* 封装了一些FTP操作
* Created by bl05973 on 2016/3/11.
*/ import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPCmd;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger; public class FTPUtil {
private static Logger logger = Logger.getLogger(FTPUtil.class); private static FTPClient getConnection() {
FTPClient client = new FTPClient();
client.setControlEncoding("UTF-8");
client.setDataTimeout(30000);
client.setDefaultTimeout(30000);
return client;
} public static FTPClient getConnection(String host) throws IOException {
FTPClient client = getConnection();
client.connect(host);
if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
throw new IOException("connect error");
}
return client;
}
public static FTPClient getConnection(String host, int port) throws IOException {
FTPClient client = getConnection();
client.connect(host, port);
if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
throw new IOException("connect error");
}
return client;
} public static FTPClient getConnection(String host, String username, String password) throws
IOException {
FTPClient client= getConnection(host);
if (StringUtil.isNotBlank(username)) {
client.login(username, password);
}
//if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
// throw new IOException("login error");
//}
return client;
} public static FTPClient getConnection(String host, int port, String username, String password)
throws IOException {
FTPClient client = getConnection(host, port);
if (StringUtil.isNotBlank(username)) {
client.login(username, password);
}
//if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
// throw new IOException("login error");
//}
return client;
} /**
* 移动文件(若目标文件存在则不移动,并返回false)
*/
public static boolean moveFile(String curFileName, String targetFileName, FTPClient client)
throws IOException {
int reply;
reply = client.sendCommand(FTPCmd.RNFR, curFileName);
if (FTPReply.isNegativePermanent(reply)) {
//logger.error("FTP move file error. code:" + reply);
System.out.println("FTP move file error. code:" + reply);
return false;
}
reply = client.sendCommand(FTPCmd.RNTO, targetFileName);
if (FTPReply.isNegativePermanent(reply)) {
//logger.error("FTP move file error. code:" + reply);
System.out.println("FTP move file error. code:" + reply);
return false;
}
return true;
} /**
* 读取文件列表
*/
public static List<String> getFileNameList(FTPClient client) throws IOException {
FTPFile[] files = client.listFiles();
List<String> fileNameList = new ArrayList<>();
for (FTPFile file : files) {
if (file.isFile()) {
fileNameList.add(file.getName());
}
}
if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
throw new IOException("get file name list error");
}
return fileNameList;
} /**
* 读文件
*/
public static String readFile(String path, FTPClient client) throws IOException {
client.setFileType(FTP.EBCDIC_FILE_TYPE);
InputStream is = client.retrieveFileStream(path);
if (is == null) {
return null;
}
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String str;
while ((str = bf.readLine()) != null) {
sb.append(str).append("\n");
}
bf.close();
client.completePendingCommand();
if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
throw new IOException("Remote file net closed success");
}
return sb.toString();
} @Deprecated
static boolean downFile(String remotePath, String localPath, FTPClient client)
throws IOException {
FileOutputStream fos = new FileOutputStream(localPath);
client.setFileType(FTPClient.BINARY_FILE_TYPE);
client.retrieveFile(remotePath, fos);
client.completePendingCommand();
if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
throw new IOException("Remote file net closed success");
}
return false;
} /**
* 写文件
*/
public static boolean storeAsFile(String context, String remotePath, FTPClient client)
throws IOException {
OutputStream out = client.storeFileStream(remotePath);
OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
writer.write(context);
writer.flush();
writer.close();
return true;
} public static void close(FTPClient client) {
try {
if (client != null) {
client.disconnect();
}
} catch (IOException e) { }
}
}
FTPUtil
[Java] 使用 Apache的 Commons-net库 实现FTP操作的更多相关文章
- Java 利用Apache Commons Net 实现 FTP文件上传下载
package woxingwosu; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ...
- cxf 报错:java.lang.NoSuchMethodError: org.apache.ws.commons.schema.XmlSchemaCollection.read(Lorg/w3c/dom/Document;Ljava/lang/String;)
由于没有仔细查看官方提供的文档,由jdk版本不一致导致的出错: http://cxf.apache.org/cxf-316-release-notes.html 自己使用的是jdk1.8. 报Exce ...
- java.lang.IllegalArgumentException: No enum constant org.apache.ws.commons.schema.XmlSchemaForm.
一次系统断电维护之后,apache cxf 的 web service 接口调用一直报错: java.lang.IllegalArgumentException: No enum constant o ...
- Java下好用的开源库推荐
作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文想介绍下自己在Java下做开发使用到的一些开源的优秀编程库,会不定 ...
- Apache Jakarta Commons 工具集简介
Apache Jakarta Commons 工具集简介[转] Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.我选了一些比较常用的项目做简单介绍.文 ...
- Apache的commons工具类
package cn.zhou; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileU ...
- java, android的aes等加密库
https://github.com/scottyab/AESCrypt-Android https://github.com/PDDStudio/EncryptedPreferences ...
- java调用c++生成的动态和静态库时遇到的问题
java.lang.UnsatisfiedLinkError: no jacob in java.library.path -Djava.library.path 关于java用jni调用 dll动态 ...
- Read / Write Excel file in Java using Apache POI
Read / Write Excel file in Java using Apache POI 2014-04-18 BY DINESH LEAVE A COMMENT About a year o ...
随机推荐
- javaScript(其他引用类型对象)
javascript其他引用类型对象 Global对象(全局)这个对象不存在,无形的对象,无法new一个 其内部定义了一些方法和属性:如下 encodeURI str = www.baidu.com ...
- PHP下的异步尝试三:协程的PHP版thunkify自动执行器
PHP下的异步尝试系列 如果你还不太了解PHP下的生成器和协程,你可以根据下面目录翻阅 PHP下的异步尝试一:初识生成器 PHP下的异步尝试二:初识协程 PHP下的异步尝试三:协程的PHP版thunk ...
- php 文件加载方式
两种加载文件的方式 include require 使用场景: 动态加载文件的时候,使用include,否则使用require. 示例: # 引入php文件--include方式 inlcude(&q ...
- 使用Storyboard实现复杂界面
http://blog.csdn.net/guchengluoye/article/details/7472771 http://wangjun.easymorse.com/?p=1564 http: ...
- webpack加载器(Loaders)
加载器(Loaders) loader 是对应用程序中资源文件进行转换.它们是(运行在 Node.js 中的)函数,可以将资源文件作为参数的来源,然后返回新的资源文件. 示例 例如,你可以使用 loa ...
- Mysql学习总结(32)——MySQL分页技术详解
1.什么是数据分页:数据分页就是将很多条记录像书本一样分页,每页显示多少行记录: 2.为什么要数据分页:当我们进行sql语句查询时,假如数据有成千上万行记录,如果在同一个页面去显示,那这个页面得有多大 ...
- 16、sockect
一.局域网因特网 服务器是指提供信息的计算机或程序,客户机是指请求信息的计算机或程序,而网络用于连接服务器与客户机,实现两者之间的通信.但有时在某个网络中很难将服务器和客户机区分开.我们通常说的“局域 ...
- java.lang.ClassNotFoundException: org.jaxen.JaxenException
java.lang.ClassNotFoundException: org.jaxen.JaxenException java.lang.ClassNotFoundException: org.jax ...
- 构建自己的AngularJS - 作用域和Digest(三)
作用域 第一章 作用域和Digest(三) $eval - 在当前作用域的上下文中运行代码 Angular有多种方式让你在当前作用域的上下文中运行代码.最简单的是$eval.传入一个函数当做其參数.然 ...
- JavaScript事件驱动机制&定时器机制
在浏览器中,事件作为一个极为重要的机制,给予JavaScript响应用户操作与DOM变化的能力.在NodeJS中.异步事件驱动模型则是提高并发能力的基础. 一.程序怎样响应事件 程序响应外部的事件有两 ...