因为最近工作中需要用到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操作的更多相关文章

  1. Java 利用Apache Commons Net 实现 FTP文件上传下载

    package woxingwosu; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ...

  2. 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 ...

  3. java.lang.IllegalArgumentException: No enum constant org.apache.ws.commons.schema.XmlSchemaForm.

    一次系统断电维护之后,apache cxf 的 web service 接口调用一直报错: java.lang.IllegalArgumentException: No enum constant o ...

  4. Java下好用的开源库推荐

    作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文想介绍下自己在Java下做开发使用到的一些开源的优秀编程库,会不定 ...

  5. Apache Jakarta Commons 工具集简介

    Apache Jakarta Commons 工具集简介[转] Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.我选了一些比较常用的项目做简单介绍.文 ...

  6. Apache的commons工具类

    package cn.zhou; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileU ...

  7. java, android的aes等加密库

    https://github.com/scottyab/AESCrypt-Android https://github.com/PDDStudio/EncryptedPreferences       ...

  8. java调用c++生成的动态和静态库时遇到的问题

    java.lang.UnsatisfiedLinkError: no jacob in java.library.path -Djava.library.path 关于java用jni调用 dll动态 ...

  9. 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 ...

随机推荐

  1. vscode快捷键补充

    ctrl+enter 快速还到下行并插入一行 ctrl+shift+enter 快速换到上行并插入一行 ctrl+~ ctrl+1 快速在终端与代码区切换 ctrl+i 选中一行 ctrl + p: ...

  2. 说说Shell在代码重构中的应用

    说说Shell在代码重构中的应用    出处信息 出处:http://blogread.cn/it/article/3426?f=wb 代码重构(Code refactoring)有时是很枯燥的,字符 ...

  3. Vue文件封装日历组件

    封装就是要具有灵活性,样式自适应,调用的时候传入props就可以变成自己想要的样式. 效果展示网址:https://1963331542.github.io/ 源代码: <template> ...

  4. AT1145 ホリドッグ

    洛谷的题解区里竟然没有O(1)做法详解-- 题面就是要判断\(1+2+\dots+n\)是不是素数 很容易让人想到上面的式子事实上等于\(n(n+1)/2\) 根据质数的定义,质数只能被1和自身整除 ...

  5. Codecademy网站安利 及 javaScript学习

    今天发现一个Code教学网站,号称可以利用零碎时间来学习些代码. codecademy (https://www.codecademy.com)

  6. ASP.NET-Razor常用方法

    1.使用Scripts.Render()引入脚本 @sectionScrits{ @Scripts.Render("~/bundles/jquery") } 2.使用@Html.H ...

  7. ZOJ 2836

    求不比M大的可以被集合任一个数整除的数的个数.(容斥原理) #include <iostream> #include <cstdio> #include <algorit ...

  8. 安装MYSQL错误“conflicts with file from package mysql-libs-*” 解决方法

    安装MYSQL的时候时: 错误现象: [root@localhost opt]# rpm -ivh MySQL-server-5.5.32-1.el6.x86_64.rpm Preparing... ...

  9. VM虚拟机上的CentOS 7系统重置root用户密码

    1.开机在进入CentOS系统时(还未进入系统内)的系统选择页面时按E键进入系统编辑模式 2.找到Linux16开头的这行代码,用方向键将光标移动至这行代码的结尾,键入一个空格和rd.break,然后 ...

  10. javascript对象的深度克隆

    在做项目的时候需要向对象里面添加新属性,又不想修改原对象.于是就写: var newObj = oldObj,但是新对象属性改变后就对象也会跟着改变,这是因为无论是新对象还是旧对象,指向的内存地址都是 ...