FtpClientHandler.java 8.4 KB

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