参考上篇文章:
《【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. }


参考链接


【SFTP】使用Jsch实现Sftp文件下载-支持断点续传和进程监控的更多相关文章

  1. 【SFTP】使用Jsch实现Sftp文件上传-支持断点续传和进程监控

    JSch是Java Secure Channel的缩写.JSch是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到 ...

  2. php大文件下载支持断点续传

    <?php   /** php下载类,支持断点续传  *  *   Func:  *   download: 下载文件  *   setSpeed: 设置下载速度  *   getRange: ...

  3. 使用JSch实现SFTP文件传输

    1.JSch开发包下载 http://www.jcraft.com/jsch/ 目前最新版本为: jsch - 0.1.51 2.简单例子,列出指定目录下的文件列表 import  java.util ...

  4. 基于JSch的Sftp工具类

    本Sftp工具类的API如下所示. 1)构造方法摘要 Sftp(String host, int port, int timeout, String username, String password ...

  5. php 支持断点续传的文件下载类

    php 支持断点续传的文件下载类 分类: php class2013-06-30 17:27 17748人阅读 评论(6) 收藏 举报 php断点续传下载http测试 php 支持断点续传,主要依靠H ...

  6. Java单线程文件下载,支持断点续传功能

    前言: 程序下载文件时,有时会因为各种各样的原因下载中断,对于小文件来说影响不大,可以快速重新下载,但是下载大文件时,就会耗费很长时间,所以断点续传功能对于大文件很有必要. 文件下载的断点续传: 1. ...

  7. jsch连接sftp后连接未释放掉问题排查

    项目中通过jsch中的sftp实现上传下载文件.在压测过程中,由于调用到sftp,下载文件不存在时,系统不断抛出异常,内存飙升,逐渐把swap区也占满,通过top监控未发现占用内存的进程,通过查找ss ...

  8. php实现的支持断点续传的文件下载类

    通常来说,php支持断点续传,主要依靠HTTP协议中 header HTTP_RANGE实现. HTTP断点续传原理: Http头 Range.Content-Range()HTTP头中一般断点下载时 ...

  9. 【FTP】FTP文件上传下载-支持断点续传

    Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...

随机推荐

  1. lumia520刷机注意事项

    1.下载后的固件名称中设备名前的随机字符都要去掉 2.安装完nokia care suit后最好在driver目录下重新双击安装usb driver

  2. 自定义Toast解决快速点击时重复弹出,排队无止尽

    解决办法:自定义MyToast类: public class MyToast { /** 之前显示的内容 */ private static String oldMsg ; /** Toast对象 * ...

  3. SIP模块版本错误问题:the sip module implements API v??? but XXX module requires API v???

    系统安装了python 2.7,继续安装PyQt4,于是依次下载sip.pyqt4源码进行安装.用以下代码测试: import PyQt4.QtGui 显示出错.错误信息:the sip module ...

  4. viewBox A-Z滚动样式

    效果图:       代码实现 (其中使用了ionic框架...) html 代码: <ion-content class='page-location'> <div class=' ...

  5. Cruehead.1

    查壳   没有 我拖 alt+F9 到上面        入口处   下断 关键跳      略过   就没了 要实现 强暴  直接过... 仔细来看看... 那两个调用   都下断   看看  判断 ...

  6. java 集合:实现

    集合本来就是为了方便开发的,实现了一些基本数据结构,一般来说数据结构有两种物理的实现:数组和链表.数组是连续的空间,链表是不连续的.基于这两种又扩展了很多的数据结构.队列,栈,hash表,树. 在ja ...

  7. Unity3d游戏场景优化杂谈(3)

    LOD(Level-of-detail)是最常用的游戏优化技术 .如果你的程序可以定制开发应用LOD的模块,当然 是很美好的事情.不过如果没有也没关系,大家可以使用UniLOD这个第三方的LOD插件. ...

  8. Mercurial笔记(hg命令)

    两个站点: http://z42.readthedocs.org/zh/latest/devtools/hg.html http://bucunzai.net/hginit/ 添加用户名 在.hg目录 ...

  9. MCMC: The Metropolis Sampler

    本文主要译自 MCMC: The Metropolis Sampler 正如之前的文章讨论的,我们可以用一个马尔可夫链来对目标分布 \(p(x)\) 进行采样,通常情况下对于很多分布 \(p(x)\) ...

  10. SQL_Server_2008修改sa密码的方法

    转载自:http://blog.csdn.net/templar1000/article/details/20211191 1. 先用Window身份验证方式登陆进去,选择数据库实例,右键选择属性—— ...