FtpClientHandler.java 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package com.primeton.damp.fileclient;
  2. import org.apache.commons.net.ftp.FTPClient;
  3. import org.apache.commons.net.ftp.FTPFile;
  4. import org.apache.commons.net.ftp.FTPReply;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.nio.file.Path;
  11. import java.nio.file.Paths;
  12. import java.util.Arrays;
  13. import java.util.Collections;
  14. import java.util.List;
  15. import java.util.Properties;
  16. import java.util.stream.Collectors;
  17. /**
  18. * Created by hadoop on 2018/8/9.
  19. */
  20. public class FtpClientHandler implements X11ClientHandler {
  21. protected static Logger logger = LoggerFactory.getLogger("FtpClientHandler");
  22. private FTPClient ftpClient;
  23. private int reply;
  24. private final String ftpHost;
  25. private final int ftpPort;
  26. private final String ftpUsername;
  27. private final String ftpPassword;
  28. public FtpClientHandler(String host,
  29. int port,
  30. String username,
  31. String password,
  32. Properties params) {
  33. ftpHost = host;
  34. ftpPort = port;
  35. ftpUsername = username;
  36. ftpPassword = password;
  37. this.reconnect(params);
  38. }
  39. /**
  40. * 以账号和密码重新连接
  41. * @param params
  42. */
  43. public void reconnect(Properties params) {
  44. try {
  45. ftpClient = new FTPClient();
  46. ftpClient.connect(ftpHost, ftpPort); //连接Ftp服务器
  47. ftpClient.login(ftpUsername, ftpPassword);
  48. ftpClient.setControlEncoding("UTF-8");
  49. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  50. ftpClient.enterLocalPassiveMode(); // 被动模式
  51. reply = ftpClient.getReplyCode();
  52. if (!FTPReply.isPositiveCompletion(reply)) {
  53. logger.info("Donot connect FTP Server, username or password is error.");
  54. ftpClient.disconnect();
  55. } else {
  56. logger.info("The FTP connect success.");
  57. }
  58. } catch (IOException e) {
  59. logger.error("ftp connect is error.", e);
  60. throw new IllegalStateException("can not connect sftp: " + ftpHost+":"+ ftpPort);
  61. }
  62. }
  63. /**
  64. * 读取文件流
  65. * @param file
  66. * @return
  67. * @throws IOException
  68. */
  69. public InputStream readFile(String file) throws IOException {
  70. return ftpClient.retrieveFileStream(file);
  71. }
  72. /**
  73. * 读取文件流
  74. * @param file
  75. * @return
  76. * @throws IOException
  77. */
  78. @Override
  79. public OutputStream writeFile(String file, boolean overwrite) throws IOException {
  80. if(overwrite) {
  81. return ftpClient.storeFileStream(file);
  82. } else {
  83. return ftpClient.appendFileStream(file);
  84. }
  85. }
  86. public boolean renameFile(String file, String newFileName) {
  87. try {
  88. return ftpClient.rename(file, newFileName);
  89. } catch (IOException e) {
  90. logger.error("Error in rename ftp file.", e);
  91. return false;
  92. }
  93. }
  94. /**
  95. * 删除文件, 返回 true 则删除成功
  96. * @param fileName
  97. */
  98. public boolean deleteFile(String fileName) {
  99. try {
  100. return ftpClient.deleteFile(fileName);
  101. } catch (IOException e) {
  102. logger.info("Delete file fail.", e);
  103. }
  104. return false;
  105. }
  106. /**
  107. * 判断目录是否存在
  108. * @param path
  109. * @return
  110. */
  111. @Override
  112. public boolean existsDir(String path) {
  113. try {
  114. FTPFile mdtmFile = ftpClient.mlistFile(path);
  115. return mdtmFile != null && mdtmFile.isDirectory();
  116. } catch (IOException e) {
  117. logger.error(e.getMessage());
  118. }
  119. return false;
  120. }
  121. /**
  122. * 判断目录是否存在
  123. * @param path
  124. * @return
  125. */
  126. @Override
  127. public boolean existsFile(String path) {
  128. try {
  129. FTPFile mdtmFile = ftpClient.mlistFile(path);
  130. return mdtmFile != null && mdtmFile.isFile();
  131. } catch (IOException e) {
  132. logger.error(e.getMessage());
  133. }
  134. return false;
  135. }
  136. /**
  137. * 判断目录或者文件是否存在
  138. * @param path
  139. * @return
  140. */
  141. @Override
  142. public boolean exists(String path) {
  143. try {
  144. final FTPFile ftpFile = ftpClient.mdtmFile(path);
  145. return ftpFile != null && ftpFile.isValid();
  146. } catch (IOException e) {
  147. logger.error(e.getMessage());
  148. }
  149. return false;
  150. }
  151. /**
  152. * 创建多层目录
  153. * @param path
  154. * @return
  155. */
  156. @Override
  157. public boolean mkdirs(String path) {
  158. Path path1 = Paths.get(path);
  159. Path parentPath = path1.getParent();
  160. if(existsDir(parentPath.toString())){
  161. return mkdir(path1.toString()); // 创建当前文件夹
  162. } else {
  163. if("/".equals(parentPath.toString()) || mkdirs(parentPath.toString())) { // 创建父级目录
  164. return mkdir(path1.toString()); // 创建当前文件夹
  165. }
  166. }
  167. // 最后创建文件夹肯定是不成功的。
  168. return existsDir(path);
  169. }
  170. /**
  171. * 创建目录, 返回 true 则创建目录成功
  172. * @param dirName 一级或者多级目录
  173. */
  174. @Override
  175. public boolean mkdir(String dirName) {
  176. try {
  177. return ftpClient.makeDirectory(dirName);
  178. } catch (IOException e) {
  179. logger.info("mkdir " + dirName + " fail.", e);
  180. }
  181. return false;
  182. }
  183. /**
  184. * 获取一个目录下或者文件的子文件
  185. * @param ftpPath
  186. * @return
  187. */
  188. @Override
  189. public List<Path> getChildren(String ftpPath) {
  190. try {
  191. FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath);
  192. List<Path> files = Arrays.stream(ftpFiles).map(it->Paths.get(ftpPath, it.getName())).collect(Collectors.toList());
  193. return files;
  194. } catch (IOException e) {
  195. logger.info("Error in scan ftpfile.");
  196. }
  197. return Collections.emptyList();
  198. }
  199. @Override
  200. public void close() throws IOException {
  201. ftpClient.disconnect();
  202. }
  203. //test
  204. public static void main(String[] args) throws IOException {
  205. Properties map = new Properties();
  206. String host = "192.168.30.143";
  207. int port = 2121;
  208. String username = "admin";
  209. String password = "primeton000000";
  210. FtpClientHandler handler = new FtpClientHandler(host, port, username, password, map);
  211. // handler.changeWorkingDirectory("/sms");
  212. List<Path> result = handler.getChildren("/DAMP");
  213. for (Path ftpFile : result) {
  214. System.out.println(ftpFile.toString());
  215. }
  216. /*
  217. OutputStream out = handler.writeFile("/hello.txt", false);
  218. IOUtils.copy(new FileInputStream("pom.xml"), out);
  219. out.flush();
  220. out.close();
  221. */
  222. System.out.println(handler.exists("/"));
  223. System.out.println(handler.exists("/hello.txt"));
  224. System.out.println(handler.exists("/example_data_1225"));
  225. System.out.println(handler.exists("/world/example_data_1225"));
  226. if(!handler.existsDir("/world/example_data_1225")) {
  227. System.out.println(handler.mkdirs("/world/example_data_1225"));
  228. }
  229. System.out.println(handler.exists("/world/example_data_1225"));
  230. }
  231. }