[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 ...
随机推荐
- laravel contains 的用法
最近在学laravel,做一下学习笔记. 1.contains()方法判断集合是否包含给定的项目: ]);var_dump($collection->contains('Desk'));// t ...
- Expressjs配置加载器
有些东西就是操刀开干,没什么好解释的.... 问题引入 解决问题 直接上码 env.js index.js 使用方法 初始化 使用方法 写在最后 问题引入 大家都知道在日常的研发过程中,我们的程序会有 ...
- HDU 4253 Two Famous Companies
Two Famous Companies Time Limit: 15000ms Memory Limit: 32768KB This problem will be judged on HDU. O ...
- 字符拆分存入Map计算单词的个数
///计算从命令行输入单词的种类与个数//Map<key,Value>Key-->单词:Value-->数量
- ASP.NET-Razor常用方法
1.使用Scripts.Render()引入脚本 @sectionScrits{ @Scripts.Render("~/bundles/jquery") } 2.使用@Html.H ...
- 洛谷 P2393 yyy loves Maths II
P2393 yyy loves Maths II 题目背景 上次蒟蒻redbag可把yyy气坏了,yyy说他只是小学生,蒟蒻redbag这次不坑他了. 题目描述 redbag给了yyy很多个数,要yy ...
- android 推断手机是否支持前置摄像头
话不多说 直接上代码, @SuppressLint("NewApi") public static boolean isSupportFrontCamera() { if (!ha ...
- ActionBarActivity设置全屏无标题
新建的Activity继承自ActionBarActivity,设置全屏无标题本来非常easy的事,可是没想到app居然无缘无故的挂,要么就是白屏一片,要么就是黑屏.坑了我一个多小时.!! 原因是Ac ...
- 用自定义的函数将gps转换为高德坐标
<?php echo<<<_END <!doctype html> <html> <head> <meta charset=" ...
- TensorFlow高层次机器学习API (tf.contrib.learn)
TensorFlow高层次机器学习API (tf.contrib.learn) 1.tf.contrib.learn.datasets.base.load_csv_with_header 加载csv格 ...