[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 ...
随机推荐
- easyUI datagrid表头的合并
图列: js代码 function initConfigTable(param){ $("#mulConfigureTableBox").empty(); $("#mul ...
- CF739E Gosha is hunting(费用流,期望)
根据期望的线性性答案就是捕捉每一只精灵的概率之和. 捕捉一只精灵的方案如下: 1.使用一个\(A\)精灵球,贡献为\(A[i]\) 2.使用一个\(B\)精灵球,贡献为\(B[i]\) 3.使用一个\ ...
- 鸟哥的linux私房菜
http://vbird.dic.ksu.edu.tw/linux_basic/linux_basic.php
- 使用Oracle Database Instant Client 精简版
如果只为了在开发环境中访问Oracle,推荐使用Oracle Database Instant Client(精简版)它相对小巧且不需要安装绿色方便移植. 官方下载Instant Client,在Or ...
- @crossorigin注解跨域
在@controller中类的头部有一个@CrossOrigin注解. @CrossOrigin是用来处理跨域请求的注解 先来说一下什么是跨域: (站在巨人的肩膀上) 跨域,指的是浏览器不能执行其他网 ...
- 安卓更新Toast流程图
今天照着书写了个程序为了理解更深刻特意画了一个流程图分享给大家 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc29uZ2p1bnlhbg==/font/5 ...
- [NIO]dawn之Task具体解释
在上篇文章中,我们设置好了开发环境,接下来.我们将在了解了Task以及Buffer之后,再開始了解网络编程.我们首先来看看Task task简单介绍 package zhmt.dawn; import ...
- 用自定义的函数将gps转换为高德坐标
<?php echo<<<_END <!doctype html> <html> <head> <meta charset=" ...
- CentOS7设置中文输入法
转自:https://i.cnblogs.com/EditPosts.aspx?postid=8327755&update=1 CentOS7设置中文输入法 安装CentOS7之后,鼓捣了半天 ...
- mfc进制转换
; CString str; m_edit1.GetWindowTextW(str); swscanf_s(str, _T("%d"), &num); _TCHAR str ...