因为最近工作中需要用到FTP操作,而手上又没有现成的FTP代码。就去网上找了一下,发现大家都使用Apache的 Commons-net库中的FTPClient。

但是,感觉用起来不太方便。又在网上找到了很多封装过的。觉得也不是很好用。于是就自己写了一个。网上大多是例子都是直接对文件进行操作,而我更需要的是读到内存,或者从内存上写。并且有很多实用单例模式,但是我觉得如果调用比较多的话,可能会出现问题。

  1. package com.best.oasis.util.helper;
  2.  
  3. /**
  4. * 封装了一些FTP操作
  5. * Created by bl05973 on 2016/3/11.
  6. */
  7.  
  8. import java.io.BufferedReader;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.io.InputStreamReader;
  13. import java.io.OutputStream;
  14. import java.io.OutputStreamWriter;
  15. import java.util.ArrayList;
  16. import java.util.List;
  17.  
  18. import org.apache.commons.net.ftp.FTP;
  19. import org.apache.commons.net.ftp.FTPClient;
  20. import org.apache.commons.net.ftp.FTPCmd;
  21. import org.apache.commons.net.ftp.FTPFile;
  22. import org.apache.commons.net.ftp.FTPReply;
  23. import org.apache.log4j.Logger;
  24.  
  25. public class FTPUtil {
  26. private static Logger logger = Logger.getLogger(FTPUtil.class);
  27.  
  28. private static FTPClient getConnection() {
  29. FTPClient client = new FTPClient();
  30. client.setControlEncoding("UTF-8");
  31. client.setDataTimeout(30000);
  32. client.setDefaultTimeout(30000);
  33. return client;
  34. }
  35.  
  36. public static FTPClient getConnection(String host) throws IOException {
  37. FTPClient client = getConnection();
  38. client.connect(host);
  39. if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
  40. throw new IOException("connect error");
  41. }
  42. return client;
  43. }
  44. public static FTPClient getConnection(String host, int port) throws IOException {
  45. FTPClient client = getConnection();
  46. client.connect(host, port);
  47. if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
  48. throw new IOException("connect error");
  49. }
  50. return client;
  51. }
  52.  
  53. public static FTPClient getConnection(String host, String username, String password) throws
  54. IOException {
  55. FTPClient client= getConnection(host);
  56. if (StringUtil.isNotBlank(username)) {
  57. client.login(username, password);
  58. }
  59. //if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
  60. // throw new IOException("login error");
  61. //}
  62. return client;
  63. }
  64.  
  65. public static FTPClient getConnection(String host, int port, String username, String password)
  66. throws IOException {
  67. FTPClient client = getConnection(host, port);
  68. if (StringUtil.isNotBlank(username)) {
  69. client.login(username, password);
  70. }
  71. //if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
  72. // throw new IOException("login error");
  73. //}
  74. return client;
  75. }
  76.  
  77. /**
  78. * 移动文件(若目标文件存在则不移动,并返回false)
  79. */
  80. public static boolean moveFile(String curFileName, String targetFileName, FTPClient client)
  81. throws IOException {
  82. int reply;
  83. reply = client.sendCommand(FTPCmd.RNFR, curFileName);
  84. if (FTPReply.isNegativePermanent(reply)) {
  85. //logger.error("FTP move file error. code:" + reply);
  86. System.out.println("FTP move file error. code:" + reply);
  87. return false;
  88. }
  89. reply = client.sendCommand(FTPCmd.RNTO, targetFileName);
  90. if (FTPReply.isNegativePermanent(reply)) {
  91. //logger.error("FTP move file error. code:" + reply);
  92. System.out.println("FTP move file error. code:" + reply);
  93. return false;
  94. }
  95. return true;
  96. }
  97.  
  98. /**
  99. * 读取文件列表
  100. */
  101. public static List<String> getFileNameList(FTPClient client) throws IOException {
  102. FTPFile[] files = client.listFiles();
  103. List<String> fileNameList = new ArrayList<>();
  104. for (FTPFile file : files) {
  105. if (file.isFile()) {
  106. fileNameList.add(file.getName());
  107. }
  108. }
  109. if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
  110. throw new IOException("get file name list error");
  111. }
  112. return fileNameList;
  113. }
  114.  
  115. /**
  116. * 读文件
  117. */
  118. public static String readFile(String path, FTPClient client) throws IOException {
  119. client.setFileType(FTP.EBCDIC_FILE_TYPE);
  120. InputStream is = client.retrieveFileStream(path);
  121. if (is == null) {
  122. return null;
  123. }
  124. BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  125. StringBuilder sb = new StringBuilder();
  126. String str;
  127. while ((str = bf.readLine()) != null) {
  128. sb.append(str).append("\n");
  129. }
  130. bf.close();
  131. client.completePendingCommand();
  132. if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
  133. throw new IOException("Remote file net closed success");
  134. }
  135. return sb.toString();
  136. }
  137.  
  138. @Deprecated
  139. static boolean downFile(String remotePath, String localPath, FTPClient client)
  140. throws IOException {
  141. FileOutputStream fos = new FileOutputStream(localPath);
  142. client.setFileType(FTPClient.BINARY_FILE_TYPE);
  143. client.retrieveFile(remotePath, fos);
  144. client.completePendingCommand();
  145. if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
  146. throw new IOException("Remote file net closed success");
  147. }
  148. return false;
  149. }
  150.  
  151. /**
  152. * 写文件
  153. */
  154. public static boolean storeAsFile(String context, String remotePath, FTPClient client)
  155. throws IOException {
  156. OutputStream out = client.storeFileStream(remotePath);
  157. OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
  158. writer.write(context);
  159. writer.flush();
  160. writer.close();
  161. return true;
  162. }
  163.  
  164. public static void close(FTPClient client) {
  165. try {
  166. if (client != null) {
  167. client.disconnect();
  168. }
  169. } catch (IOException e) {
  170.  
  171. }
  172. }
  173. }

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. easyUI datagrid表头的合并

    图列: js代码 function initConfigTable(param){ $("#mulConfigureTableBox").empty(); $("#mul ...

  2. CF739E Gosha is hunting(费用流,期望)

    根据期望的线性性答案就是捕捉每一只精灵的概率之和. 捕捉一只精灵的方案如下: 1.使用一个\(A\)精灵球,贡献为\(A[i]\) 2.使用一个\(B\)精灵球,贡献为\(B[i]\) 3.使用一个\ ...

  3. 鸟哥的linux私房菜

    http://vbird.dic.ksu.edu.tw/linux_basic/linux_basic.php

  4. 使用Oracle Database Instant Client 精简版

    如果只为了在开发环境中访问Oracle,推荐使用Oracle Database Instant Client(精简版)它相对小巧且不需要安装绿色方便移植. 官方下载Instant Client,在Or ...

  5. @crossorigin注解跨域

    在@controller中类的头部有一个@CrossOrigin注解. @CrossOrigin是用来处理跨域请求的注解 先来说一下什么是跨域: (站在巨人的肩膀上) 跨域,指的是浏览器不能执行其他网 ...

  6. 安卓更新Toast流程图

    今天照着书写了个程序为了理解更深刻特意画了一个流程图分享给大家 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc29uZ2p1bnlhbg==/font/5 ...

  7. [NIO]dawn之Task具体解释

    在上篇文章中,我们设置好了开发环境,接下来.我们将在了解了Task以及Buffer之后,再開始了解网络编程.我们首先来看看Task task简单介绍 package zhmt.dawn; import ...

  8. 用自定义的函数将gps转换为高德坐标

    <?php echo<<<_END <!doctype html> <html> <head> <meta charset=" ...

  9. CentOS7设置中文输入法

    转自:https://i.cnblogs.com/EditPosts.aspx?postid=8327755&update=1 CentOS7设置中文输入法 安装CentOS7之后,鼓捣了半天 ...

  10. mfc进制转换

    ; CString str; m_edit1.GetWindowTextW(str); swscanf_s(str, _T("%d"), &num); _TCHAR str ...