SftpClientHandler.java 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package com.primeton.damp.fileclient;
  2. import com.google.common.collect.Lists;
  3. import org.apache.sshd.client.subsystem.sftp.fs.SftpFileSystemProvider;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import java.io.IOException;
  7. import java.io.OutputStream;
  8. import java.nio.file.*;
  9. import java.util.*;
  10. import static java.nio.file.StandardOpenOption.APPEND;
  11. import static java.nio.file.StandardOpenOption.CREATE;
  12. /**
  13. * Created by hadoop on 2018/8/9.
  14. */
  15. public class SftpClientHandler implements X11ClientHandler {
  16. protected static Logger logger = LoggerFactory.getLogger("SftpClientHandler");
  17. private final String sftpHost;
  18. private final int sftpPort;
  19. private final String ftpUsername;
  20. private final String ftpPassword;
  21. /**
  22. * sftp 文件系统
  23. */
  24. FileSystem fs;
  25. public SftpClientHandler(String host,
  26. int port,
  27. String username,
  28. String password,
  29. Properties params) {
  30. sftpHost = host;
  31. sftpPort = port;
  32. ftpUsername = username;
  33. ftpPassword = password;
  34. this.reconnect(params);
  35. }
  36. /**
  37. * 以账号和密码重新连接
  38. * @param params
  39. */
  40. @Override
  41. public void reconnect(Properties params) {
  42. java.net.URI uri = SftpFileSystemProvider.createFileSystemURI(this.sftpHost, sftpPort, ftpUsername, ftpPassword);
  43. try {
  44. fs = FileSystems.newFileSystem(uri, (Map) params);
  45. } catch (FileSystemAlreadyExistsException e){
  46. logger.warn("exists file system sftp...");
  47. fs = FileSystems.getFileSystem(uri);
  48. } catch (IOException e) {
  49. logger.error("ftp connect is error.", e);
  50. throw new IllegalStateException("can not connect sftp: " + sftpHost+":"+ sftpPort);
  51. }
  52. }
  53. /**
  54. * 读取文件流
  55. * @param file
  56. * @return
  57. * @throws IOException
  58. */
  59. @Override
  60. public OutputStream writeFile(String file, boolean overwrite) throws IOException {
  61. Path path1 = fs.getPath(file);
  62. if(overwrite) {
  63. return Files.newOutputStream(path1, CREATE);
  64. } else {
  65. return Files.newOutputStream(path1, APPEND);
  66. }
  67. }
  68. public boolean renameFile(String file, String newFileName) {
  69. try {
  70. Path path1 = fs.getPath(file);
  71. Path path = Paths.get(path1.getParent().toString(), newFileName);
  72. Files.move(path, path1);
  73. return true;
  74. } catch (Exception e) {
  75. logger.error("Error in rename ftp file.", e);
  76. return false;
  77. }
  78. }
  79. /**
  80. * 删除文件, 返回 true 则删除成功
  81. * @param path
  82. */
  83. public boolean deleteFile(String path) {
  84. try {
  85. Path path1 = fs.getPath(path);
  86. Files.delete(path1);
  87. } catch (Exception e) {
  88. logger.info("Delete file fail.", e);
  89. }
  90. return false;
  91. }
  92. /**
  93. * 判断目录是否存在
  94. * @param path
  95. * @return
  96. */
  97. @Override
  98. public boolean existsDir(String path) {
  99. try {
  100. Path path1 = fs.getPath(path);
  101. return Files.exists(path1) && Files.isDirectory(path1);
  102. } catch (Exception e) {
  103. }
  104. return false;
  105. }
  106. /**
  107. * 判断目录是否存在
  108. * @param path
  109. * @return
  110. */
  111. @Override
  112. public boolean existsFile(String path) {
  113. try {
  114. Path path1 = fs.getPath(path);
  115. return Files.exists(path1) && Files.isRegularFile(path1);
  116. } catch (Exception e) {
  117. }
  118. return false;
  119. }
  120. /**
  121. * 判断目录或者文件是否存在
  122. * @param path
  123. * @return
  124. */
  125. @Override
  126. public boolean exists(String path) {
  127. try {
  128. Path path1 = fs.getPath(path);
  129. return Files.exists(path1);
  130. } catch (Exception e) {
  131. }
  132. return false;
  133. }
  134. /**
  135. * 创建多层目录
  136. * @param path
  137. * @return
  138. */
  139. @Override
  140. public boolean mkdirs(String path) {
  141. Path path1 = fs.getPath(path);
  142. Path parentPath = path1.getParent();
  143. if(parentPath == null) {
  144. // parentPath 等于 null 则说明是文件系统的根目录了。
  145. return true;
  146. }
  147. // 父级目录已经存在,只创建当前目录
  148. if(existsDir(parentPath.toString())){
  149. return mkdir(path1.toString()); // 创建当前文件夹
  150. } else {
  151. // 父级目录不存在,则先创建父级目录,再创建当前目录
  152. if(mkdirs(parentPath.toString())) { // 创建父级目录
  153. return mkdir(path1.toString()); // 创建当前文件夹
  154. }
  155. }
  156. // 最后创建文件夹肯定是不成功的。
  157. return existsDir(path);
  158. }
  159. /**
  160. * 创建目录, 返回 true 则创建目录成功
  161. * @param dirName 一级或者多级目录
  162. */
  163. @Override
  164. public boolean mkdir(String dirName) {
  165. try {
  166. Path path1 = fs.getPath(dirName);
  167. Files.createDirectory(path1);
  168. return true;
  169. } catch (IOException e) {
  170. logger.info("mkdir " + dirName + " fail.", e);
  171. }
  172. return false;
  173. }
  174. /**
  175. * 获取一个目录下或者文件的子文件
  176. * @param ftpPath
  177. * @return
  178. */
  179. @Override
  180. public List<Path> getChildren(String ftpPath) {
  181. Path remotePath = fs.getPath(ftpPath);
  182. try {
  183. DirectoryStream<Path> paths = Files.newDirectoryStream(remotePath);
  184. return Lists.newArrayList(paths.iterator());
  185. } catch (IOException e) {
  186. logger.info("Error in scan sftpfile.");
  187. }
  188. return Collections.emptyList();
  189. }
  190. @Override
  191. public void close() throws IOException {
  192. logger.warn("close the file system");
  193. fs.close();
  194. }
  195. public static void main(String[] args) {
  196. Properties map = new Properties();
  197. String host = "localhost";
  198. int port = 2121;
  199. String username = "admin";
  200. String password = "admin";
  201. SftpClientHandler handler = new SftpClientHandler(host, port, username, password, map);
  202. // handler.changeWorkingDirectory("/sms");
  203. List<Path> result = handler.getChildren("/");
  204. /*
  205. OutputStream out = handler.writeFile("/hello.txt", false);
  206. IOUtils.copy(new FileInputStream("pom.xml"), out);
  207. out.flush();
  208. out.close();
  209. */
  210. handler.exists("/hello.txt");
  211. handler.exists("/example_data_1225");
  212. handler.exists("/world/example_data_1225");
  213. handler.mkdirs("/world/example_data_1225");
  214. handler.exists("/world/example_data_1225");
  215. }
  216. }