【SFTP】使用Jsch實現Sftp文件下載-支持斷點續傳和進程監控


參考上篇文章:
《【SFTP】使用Jsch實現Sftp文件下載-支持斷點續傳和進程監控》: http://www.cnblogs.com/ssslinppp/p/6248763.html  


文件下載


測試斷點續傳




完整程序

     
     
     
             
  1. package com.sssppp.Communication;
  2. /**
  3. * This program will demonstrate the sftp protocol support.
  4. * $ CLASSPATH=.:../build javac Sftp.java
  5. * $ CLASSPATH=.:../build java Sftp
  6. * You will be asked username, host and passwd.
  7. * If everything works fine, you will get a prompt 'sftp>'.
  8. * 'help' command will show available command.
  9. * In current implementation, the destination path for 'get' and 'put'
  10. * commands must be a file, not a directory.
  11. *
  12. */
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import java.util.Properties;
  16. import javax.swing.ProgressMonitor;
  17. import com.jcraft.jsch.Channel;
  18. import com.jcraft.jsch.ChannelSftp;
  19. import com.jcraft.jsch.JSch;
  20. import com.jcraft.jsch.JSchException;
  21. import com.jcraft.jsch.Session;
  22. import com.jcraft.jsch.SftpProgressMonitor;
  23. /**
  24. * <pre>
  25. * ----------命令集合---------------------
  26. * 可參考鏈接(官方示例程序):http://www.jcraft.com/jsch/examples/Sftp.java
  27. * ChannelSftp c = (ChannelSftp) channel;
  28. * c.quit();
  29. * c.exit();
  30. * c.cd("/home/example");
  31. * c.lcd("/home/example");
  32. * c.rm("/home/example.gz");
  33. * c.rmdir("/home/example");
  34. * c.mkdir("/home/example");
  35. * c.chgrp(777, "/home/example");
  36. * c.chown(777, "/home/example");
  37. * c.chmod(777, "/home/example");
  38. * c.pwd();
  39. * c.lpwd();
  40. * c.ls("/home/example");
  41. *
  42. * SftpProgressMonitor monitor = new MyProgressMonitor(); //顯示進度
  43. * //文件下載
  44. * c.get("srcPath", "dstPath", monitor, ChannelSftp.OVERWRITE);
  45. * c.get("srcPath", "dstPath", monitor, ChannelSftp.RESUME); //斷點續傳
  46. * c.get("srcPath", "dstPath", monitor, ChannelSftp.APPEND);
  47. * //文件上傳
  48. * c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND);
  49. * c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND);
  50. * c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND);
  51. *
  52. * c.hardlink("oldPath", "newPath");
  53. * c.rename("oldPath", "newPath");
  54. * c.symlink("oldPath", "newPath");
  55. * c.readlink("Path");
  56. * c.realpath("Path");
  57. * c.version();
  58. *
  59. * SftpStatVFS stat = c.statVFS("path"); //df 命令
  60. * long size = stat.getSize();
  61. * long used = stat.getUsed();
  62. * long avail = stat.getAvailForNonRoot();
  63. * long root_avail = stat.getAvail();
  64. * long capacity = stat.getCapacity();
  65. *
  66. * c.stat("path");
  67. * c.lstat("path");
  68. * ----------------------------------------------------------------------
  69. * </pre>
  70. *
  71. */
  72. public class SftpUtil {
  73. Session session = null;
  74. Channel channel = null;
  75. public static final String SFTP_REQ_HOST = "host";
  76. public static final String SFTP_REQ_PORT = "port";
  77. public static final String SFTP_REQ_USERNAME = "username";
  78. public static final String SFTP_REQ_PASSWORD = "password";
  79. public static final int SFTP_DEFAULT_PORT = 22;
  80. public static final String SFTP_REQ_LOC = "location";
  81. /**
  82. * 測試程序
  83. * @param arg
  84. * @throws Exception
  85. */
  86. public static void main(String[] arg) throws Exception {
  87. // 設置主機ip,端口,用戶名,密碼
  88. Map<String, String> sftpDetails = new HashMap<String, String>();
  89. sftpDetails.put(SFTP_REQ_HOST, "10.180.137.221");
  90. sftpDetails.put(SFTP_REQ_USERNAME, "root");
  91. sftpDetails.put(SFTP_REQ_PASSWORD, "xxxx");
  92. sftpDetails.put(SFTP_REQ_PORT, "22");
  93. //測試文件上傳
  94. String src = "C:\\xxx\\TMP\\site-1.10.4.zip"; // 本地文件名
  95. String dst = "/tmp/sftp/"; // 目標文件名
  96. uploadFile(src, dst, sftpDetails);
  97. //測試文件下載
  98. String srcFilename = "/tmp/sftp/site-1.10.4.zip";
  99. String dstFilename = "C:\\tmp\\site-1.10.4-new.zip";
  100. downloadFile(srcFilename, dstFilename, sftpDetails);
  101. }
  102. public static void downloadFile(String src, String dst,
  103. Map<String, String> sftpDetails) throws Exception {
  104. SftpUtil sftpUtil = new SftpUtil();
  105. ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 160000);
  106. // Retrieves the file attributes of a file or directory
  107. // SftpATTRS attr = chSftp.stat(src);
  108. // long fileSize = attr.getSize();
  109. //代碼段1/代碼段2/代碼段3:分別演示了如何使用JSch的各種put方法來進行文件下載
  110. try {
  111. // 代碼段1:使用這個方法時,dst可以是目錄,若dst為目錄,則下載到本地的文件名將與src文件名相同
  112. chSftp.get(src, dst, new MyProgressMonitor(),ChannelSftp.RESUME); //斷點續傳
  113. /***
  114. OutputStream out = new FileOutputStream(dst);
  115. // 代碼段2:將目標服務器上文件名為src的文件下載到本地的一個輸出流對象,該輸出流為一個文件輸出流
  116. chSftp.get(src, out, new MyProgressMonitor());
  117. // 代碼段3:采用讀取get方法返回的輸入流數據的方式來下載文件
  118. InputStream is = chSftp.get(src, new MyProgressMonitor(),ChannelSftp.RESUME);
  119. byte[] buff = new byte[1024 * 2];
  120. int read;
  121. if (is != null) {
  122. do {
  123. read = is.read(buff, 0, buff.length);
  124. if (read > 0) {
  125. out.write(buff, 0, read);
  126. }
  127. out.flush();
  128. } while (read >= 0);
  129. }
  130. **/
  131. } catch (Exception e) {
  132. e.printStackTrace();
  133. } finally {
  134. chSftp.quit();
  135. sftpUtil.closeChannel();
  136. }
  137. }
  138. public static void uploadFile(String src, String dst,
  139. Map<String, String> sftpDetails) throws Exception {
  140. SftpUtil sftpUtil = new SftpUtil();
  141. ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 60000);
  142. /**
  143. * 代碼段1/代碼段2/代碼段3分別演示了如何使用JSch的不同的put方法來進行文件上傳。這三段代碼實現的功能是一樣的,
  144. * 都是將本地的文件src上傳到了服務器的dst文件
  145. */
  146. /**代碼段1
  147. OutputStream out = chSftp.put(dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式
  148. byte[] buff = new byte[1024 * 256]; // 設定每次傳輸的數據塊大小為256KB
  149. int read;
  150. if (out != null) {
  151. InputStream is = new FileInputStream(src);
  152. do {
  153. read = is.read(buff, 0, buff.length);
  154. if (read > 0) {
  155. out.write(buff, 0, read);
  156. }
  157. out.flush();
  158. } while (read >= 0);
  159. }
  160. **/
  161. // 使用這個方法時,dst可以是目錄,當dst是目錄時,上傳后的目標文件名將與src文件名相同
  162. // ChannelSftp.RESUME:斷點續傳
  163. chSftp.put(src, dst, new MyProgressMonitor(), ChannelSftp.RESUME); // 代碼段2
  164. // 將本地文件名為src的文件輸入流上傳到目標服務器,目標文件名為dst
  165. // chSftp.put(new FileInputStream(src), dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 代碼段3
  166. chSftp.quit();
  167. sftpUtil.closeChannel();
  168. }
  169. /**
  170. * 根據ip,用戶名及密碼得到一個SFTP
  171. * channel對象,即ChannelSftp的實例對象,在應用程序中就可以使用該對象來調用SFTP的各種操作方法
  172. *
  173. * @param sftpDetails
  174. * @param timeout
  175. * @return
  176. * @throws JSchException
  177. */
  178. public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout)
  179. throws JSchException {
  180. String ftpHost = sftpDetails.get(SFTP_REQ_HOST);
  181. String port = sftpDetails.get(SFTP_REQ_PORT);
  182. String ftpUserName = sftpDetails.get(SFTP_REQ_USERNAME);
  183. String ftpPassword = sftpDetails.get(SFTP_REQ_PASSWORD);
  184. int ftpPort = SFTP_DEFAULT_PORT;
  185. if (port != null && !port.equals("")) {
  186. ftpPort = Integer.valueOf(port);
  187. }
  188. JSch jsch = new JSch(); // 創建JSch對象
  189. session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根據用戶名,主機ip,端口獲取一個Session對象
  190. if (ftpPassword != null) {
  191. session.setPassword(ftpPassword); // 設置密碼
  192. }
  193. Properties config = new Properties();
  194. config.put("StrictHostKeyChecking", "no");
  195. session.setConfig(config); // Session對象設置properties
  196. session.setTimeout(timeout); // 設置timeout時間
  197. session.connect(5000); // 通過Session建立鏈接
  198. channel = session.openChannel("sftp"); // 打開SFTP通道
  199. channel.connect(); // 建立SFTP通道的連接
  200. return (ChannelSftp) channel;
  201. }
  202. public void closeChannel() throws Exception {
  203. if (channel != null) {
  204. channel.disconnect();
  205. }
  206. if (session != null) {
  207. session.disconnect();
  208. }
  209. }
  210. /**
  211. * 進度監控器-JSch每次傳輸一個數據塊,就會調用count方法來實現主動進度通知
  212. *
  213. */
  214. public static class MyProgressMonitor implements SftpProgressMonitor {
  215. private long count = 0; //當前接收的總字節數
  216. private long max = 0; //最終文件大小
  217. private long percent = -1; //進度
  218. /**
  219. * 當每次傳輸了一個數據塊后,調用count方法,count方法的參數為這一次傳輸的數據塊大小
  220. */
  221. @Override
  222. public boolean count(long count) {
  223. this.count += count;
  224. if (percent >= this.count * 100 / max) {
  225. return true;
  226. }
  227. percent = this.count * 100 / max;
  228. System.out.println("Completed " + this.count + "(" + percent
  229. + "%) out of " + max + ".");
  230. return true;
  231. }
  232. /**
  233. * 當傳輸結束時,調用end方法
  234. */
  235. @Override
  236. public void end() {
  237. System.out.println("Transferring done.");
  238. }
  239. /**
  240. * 當文件開始傳輸時,調用init方法
  241. */
  242. @Override
  243. public void init(int op, String src, String dest, long max) {
  244. if (op==SftpProgressMonitor.PUT) {
  245. System.out.println("Upload file begin.");
  246. }else {
  247. System.out.println("Download file begin.");
  248. }
  249. this.max = max;
  250. this.count = 0;
  251. this.percent = -1;
  252. }
  253. }
  254. /**
  255. * 官方提供的進度監控器
  256. *
  257. */
  258. public static class DemoProgressMonitor implements SftpProgressMonitor {
  259. ProgressMonitor monitor;
  260. long count = 0;
  261. long max = 0;
  262. /**
  263. * 當文件開始傳輸時,調用init方法。
  264. */
  265. public void init(int op, String src, String dest, long max) {
  266. this.max = max;
  267. monitor = new ProgressMonitor(null,
  268. ((op == SftpProgressMonitor.PUT) ? "put" : "get") + ": "
  269. + src, "", 0, (int) max);
  270. count = 0;
  271. percent = -1;
  272. monitor.setProgress((int) this.count);
  273. monitor.setMillisToDecideToPopup(1000);
  274. }
  275. private long percent = -1;
  276. /**
  277. * 當每次傳輸了一個數據塊后,調用count方法,count方法的參數為這一次傳輸的數據塊大小。
  278. */
  279. public boolean count(long count) {
  280. this.count += count;
  281. if (percent >= this.count * 100 / max) {
  282. return true;
  283. }
  284. percent = this.count * 100 / max;
  285. monitor.setNote("Completed " + this.count + "(" + percent
  286. + "%) out of " + max + ".");
  287. monitor.setProgress((int) this.count);
  288. return !(monitor.isCanceled());
  289. }
  290. /**
  291. * 當傳輸結束時,調用end方法。
  292. */
  293. public void end() {
  294. monitor.close();
  295. }
  296. }
  297. }


參考鏈接







免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM