当前位置: 首页 > 工具软件 > Commons-VFS > 使用案例 >

使用 Apache Commons VFS 來操作 SFTP

齐意致
2023-12-01

原文链接:http://pro.ctlok.com/2011/06/apache-commons-vfs-for-sftp.html

在 Java 使用 FTP 去上載檔案,下載檔案或去做其他操作也是很簡單,因為 Java API 已經包括了對 FTP 的支援。如果不是使用 FTP,而是使用 SFTP: SSH File Transfer Protocol,使用Java API 實作便有點麻煩了。

幸好 Apache Commons VFS 替我們實作了 SFTP 的操作,Apache Commons VFS 配合 JSch 使我們可以很簡單地使用 SSH 連接 Server 和上載檔案,下載檔案等等操作。

廢話不多說,首先要準備 3 個 Library:


下載好後將  .jar  加到  class path  令程式找到這些  Library

再來就是寫程式,為了方便好看,我會將所有程式碼放到  Main class  內。

第一步是製作一個  Function  去將  Protocol Host Name Username Password  和  Server  上的檔案位置連接起來 (Factory Method)。令到  Apache Commons VFS  能讀得懂。

  
  
  1. public static String createConnectionString(String hostName,
  2. String username, String password, String remoteFilePath) {
  3. // result: "sftp://user:123456@domainname.com/resume.pdf
  4. return "sftp://" + username + ":" + password + "@" + hostName + "/"
  5. + remoteFilePath;
  6. }

第二步是製作一個  Function  去製造出一個  SFTP  預設的設定 (Factory Method):

  
  
  1. public static FileSystemOptions createDefaultOptions()
  2. throws FileSystemException {
  3. // Create SFTP options
  4. FileSystemOptions opts = new FileSystemOptions();
  5.  
  6. // SSH Key checking
  7. SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
  8. opts, "no");
  9.  
  10. // Root directory set to user home
  11. SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
  12.  
  13. // Timeout is count by Milliseconds
  14. SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
  15.  
  16. return opts;
  17. }

第三步是製作一個上載檔案的  Function :

  
  
  1. public static void upload(String hostName, String username,
  2. String password, String localFilePath, String remoteFilePath) {
  3.  
  4. File f = new File(localFilePath);
  5. if (!f.exists())
  6. throw new RuntimeException("Error. Local file not found");
  7.  
  8. StandardFileSystemManager manager = new StandardFileSystemManager();
  9.  
  10. try {
  11. manager.init();
  12.  
  13. // Create local file object
  14. FileObject localFile = manager.resolveFile(f.getAbsolutePath());
  15.  
  16. // Create remote file object
  17. FileObject remoteFile = manager.resolveFile(
  18. createConnectionString(hostName, username, password,
  19. remoteFilePath), createDefaultOptions());
  20.  
  21. // Copy local file to sftp server
  22. remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
  23.  
  24. System.out.println("File upload success");
  25. } catch (Exception e) {
  26. throw new RuntimeException(e);
  27. } finally {
  28. manager.close();
  29. }
  30. }

在這裡可以測試一下上載檔案的  Function  是否沒有問題:

  
  
  1. /*
  2. * args[0]: hostName
  3. * args[1]: username
  4. * args[2]: password
  5. * args[3]:localFilePath
  6. * args[4]: remoteFilePath
  7. */
  8. public static void main(String[] args) {
  9. if (args.length < 5)
  10. throw new RuntimeException(
  11. "Error. Please enter "
  12. + "args[0]: hostName, args[1]: username, args[2]: password, "
  13. + "args[3]: localFilePath, args[4]: remoteFilePath.");
  14.  
  15. upload(args[0], args[1], args[2], args[3], args[4]);
  16. }

成功後  Console  會打印出  File upload success

再來是加下載檔案的  Function :

  
  
  1. public static void download(String hostName, String username,
  2. String password, String localFilePath, String remoteFilePath) {
  3.  
  4. StandardFileSystemManager manager = new StandardFileSystemManager();
  5.  
  6. try {
  7. manager.init();
  8.  
  9. String downloadFilePath = localFilePath.substring(0,
  10. localFilePath.lastIndexOf("."))
  11. + "_downlaod_from_sftp"
  12. + localFilePath.substring(localFilePath.lastIndexOf("."),
  13. localFilePath.length());
  14.  
  15. // Create local file object
  16. FileObject localFile = manager.resolveFile(downloadFilePath);
  17.  
  18. // Create remote file object
  19. FileObject remoteFile = manager.resolveFile(
  20. createConnectionString(hostName, username, password,
  21. remoteFilePath), createDefaultOptions());
  22.  
  23. // Copy local file to sftp server
  24. localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
  25.  
  26. System.out.println("File download success");
  27. } catch (Exception e) {
  28. throw new RuntimeException(e);
  29. } finally {
  30. manager.close();
  31. }
  32. }

測試檔案是否存在的  Function :

  
  
  1. public static boolean exist(String hostName, String username,
  2. String password, String remoteFilePath) {
  3. StandardFileSystemManager manager = new StandardFileSystemManager();
  4.  
  5. try {
  6. manager.init();
  7.  
  8. // Create remote object
  9. FileObject remoteFile = manager.resolveFile(
  10. createConnectionString(hostName, username, password,
  11. remoteFilePath), createDefaultOptions());
  12.  
  13. System.out.println("File exist: " + remoteFile.exists());
  14.  
  15. return remoteFile.exists();
  16. } catch (Exception e) {
  17. throw new RuntimeException(e);
  18. } finally {
  19. manager.close();
  20. }
  21. }

刪除  Server  檔案的  Function :

  
  
  1. public static void delete(String hostName, String username,
  2. String password, String remoteFilePath) {
  3. StandardFileSystemManager manager = new StandardFileSystemManager();
  4.  
  5. try {
  6. manager.init();
  7.  
  8. // Create remote object
  9. FileObject remoteFile = manager.resolveFile(
  10. createConnectionString(hostName, username, password,
  11. remoteFilePath), createDefaultOptions());
  12.  
  13. if (remoteFile.exists()) {
  14. remoteFile.delete();
  15. System.out.println("Delete remote file success");
  16. }
  17. } catch (Exception e) {
  18. throw new RuntimeException(e);
  19. } finally {
  20. manager.close();
  21. }
  22. }

完整的程式:

  
  
  1. package sftp.sample;
  2.  
  3. import java.io.File;
  4.  
  5. import org.apache.commons.vfs.FileObject;
  6. import org.apache.commons.vfs.FileSystemException;
  7. import org.apache.commons.vfs.FileSystemOptions;
  8. import org.apache.commons.vfs.Selectors;
  9. import org.apache.commons.vfs.impl.StandardFileSystemManager;
  10. import org.apache.commons.vfs.provider.sftp.SftpFileSystemConfigBuilder;
  11.  
  12. public class Main {
  13.  
  14. /*
  15. * args[0]: hostName
  16. * args[1]: username
  17. * args[2]: password
  18. * args[3]: localFilePath
  19. * args[4]: remoteFilePath
  20. */
  21. public static void main(String[] args) {
  22. if (args.length < 5)
  23. throw new RuntimeException(
  24. "Error. Please enter "
  25. + "args[0]: hostName, args[1]: username, args[2]: password, "
  26. + "args[3]: localFilePath, args[4]: remoteFilePath.");
  27.  
  28. upload(args[0], args[1], args[2], args[3], args[4]);
  29. exist(args[0], args[1], args[2], args[4]);
  30. download(args[0], args[1], args[2], args[3], args[4]);
  31. delete(args[0], args[1], args[2], args[4]);
  32. }
  33.  
  34. public static void upload(String hostName, String username,
  35. String password, String localFilePath, String remoteFilePath) {
  36.  
  37. File f = new File(localFilePath);
  38. if (!f.exists())
  39. throw new RuntimeException("Error. Local file not found");
  40.  
  41. StandardFileSystemManager manager = new StandardFileSystemManager();
  42.  
  43. try {
  44. manager.init();
  45.  
  46. // Create local file object
  47. FileObject localFile = manager.resolveFile(f.getAbsolutePath());
  48.  
  49. // Create remote file object
  50. FileObject remoteFile = manager.resolveFile(
  51. createConnectionString(hostName, username, password,
  52. remoteFilePath), createDefaultOptions());
  53.  
  54. // Copy local file to sftp server
  55. remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
  56.  
  57. System.out.println("File upload success");
  58. } catch (Exception e) {
  59. throw new RuntimeException(e);
  60. } finally {
  61. manager.close();
  62. }
  63. }
  64.  
  65. public static void download(String hostName, String username,
  66. String password, String localFilePath, String remoteFilePath) {
  67.  
  68. StandardFileSystemManager manager = new StandardFileSystemManager();
  69.  
  70. try {
  71. manager.init();
  72.  
  73. String downloadFilePath = localFilePath.substring(0,
  74. localFilePath.lastIndexOf("."))
  75. + "_downlaod_from_sftp"
  76. + localFilePath.substring(localFilePath.lastIndexOf("."),
  77. localFilePath.length());
  78.  
  79. // Create local file object
  80. FileObject localFile = manager.resolveFile(downloadFilePath);
  81.  
  82. // Create remote file object
  83. FileObject remoteFile = manager.resolveFile(
  84. createConnectionString(hostName, username, password,
  85. remoteFilePath), createDefaultOptions());
  86.  
  87. // Copy local file to sftp server
  88. localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
  89.  
  90. System.out.println("File download success");
  91. } catch (Exception e) {
  92. throw new RuntimeException(e);
  93. } finally {
  94. manager.close();
  95. }
  96. }
  97.  
  98. public static void delete(String hostName, String username,
  99. String password, String remoteFilePath) {
  100. StandardFileSystemManager manager = new StandardFileSystemManager();
  101.  
  102. try {
  103. manager.init();
  104.  
  105. // Create remote object
  106. FileObject remoteFile = manager.resolveFile(
  107. createConnectionString(hostName, username, password,
  108. remoteFilePath), createDefaultOptions());
  109.  
  110. if (remoteFile.exists()) {
  111. remoteFile.delete();
  112. System.out.println("Delete remote file success");
  113. }
  114. } catch (Exception e) {
  115. throw new RuntimeException(e);
  116. } finally {
  117. manager.close();
  118. }
  119. }
  120.  
  121. public static boolean exist(String hostName, String username,
  122. String password, String remoteFilePath) {
  123. StandardFileSystemManager manager = new StandardFileSystemManager();
  124.  
  125. try {
  126. manager.init();
  127.  
  128. // Create remote object
  129. FileObject remoteFile = manager.resolveFile(
  130. createConnectionString(hostName, username, password,
  131. remoteFilePath), createDefaultOptions());
  132.  
  133. System.out.println("File exist: " + remoteFile.exists());
  134.  
  135. return remoteFile.exists();
  136. } catch (Exception e) {
  137. throw new RuntimeException(e);
  138. } finally {
  139. manager.close();
  140. }
  141. }
  142.  
  143. public static String createConnectionString(String hostName,
  144. String username, String password, String remoteFilePath) {
  145. // result: "sftp://user:123456@domainname.com/resume.pdf
  146. return "sftp://" + username + ":" + password + "@" + hostName + "/"
  147. + remoteFilePath;
  148. }
  149.  
  150. public static FileSystemOptions createDefaultOptions()
  151. throws FileSystemException {
  152. // Create SFTP options
  153. FileSystemOptions opts = new FileSystemOptions();
  154.  
  155. // SSH Key checking
  156. SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
  157. opts, "no");
  158.  
  159. // Root directory set to user home
  160. SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
  161.  
  162. // Timeout is count by Milliseconds
  163. SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
  164.  
  165. return opts;
  166. }
  167.  
  168. }

 类似资料: