【SFTP】使用Jsch实现Sftp文件下载-支持断点续传和进程监控
文件下载
测试断点续传
完整程序
package com.sssppp.Communication;/*** This program will demonstrate the sftp protocol support.* $ CLASSPATH=.:../build javac Sftp.java* $ CLASSPATH=.:../build java Sftp* You will be asked username, host and passwd.* If everything works fine, you will get a prompt 'sftp>'.* 'help' command will show available command.* In current implementation, the destination path for 'get' and 'put'* commands must be a file, not a directory.**/import java.util.HashMap;import java.util.Map;import java.util.Properties;import javax.swing.ProgressMonitor;import com.jcraft.jsch.Channel;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSch;import com.jcraft.jsch.JSchException;import com.jcraft.jsch.Session;import com.jcraft.jsch.SftpProgressMonitor;/*** <pre>* ----------命令集合---------------------* 可参考链接(官方示例程序):http://www.jcraft.com/jsch/examples/Sftp.java* ChannelSftp c = (ChannelSftp) channel;* c.quit();* c.exit();* c.cd("/home/example");* c.lcd("/home/example");* c.rm("/home/example.gz");* c.rmdir("/home/example");* c.mkdir("/home/example");* c.chgrp(777, "/home/example");* c.chown(777, "/home/example");* c.chmod(777, "/home/example");* c.pwd();* c.lpwd();* c.ls("/home/example");** SftpProgressMonitor monitor = new MyProgressMonitor(); //显示进度* //文件下载* c.get("srcPath", "dstPath", monitor, ChannelSftp.OVERWRITE);* c.get("srcPath", "dstPath", monitor, ChannelSftp.RESUME); //断点续传* c.get("srcPath", "dstPath", monitor, ChannelSftp.APPEND);* //文件上传* c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND);* c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND);* c.put("srcPath", "dstPath", monitor, ChannelSftp.APPEND);** c.hardlink("oldPath", "newPath");* c.rename("oldPath", "newPath");* c.symlink("oldPath", "newPath");* c.readlink("Path");* c.realpath("Path");* c.version();** SftpStatVFS stat = c.statVFS("path"); //df 命令* long size = stat.getSize();* long used = stat.getUsed();* long avail = stat.getAvailForNonRoot();* long root_avail = stat.getAvail();* long capacity = stat.getCapacity();** c.stat("path");* c.lstat("path");* ----------------------------------------------------------------------* </pre>**/public class SftpUtil {Session session = null;Channel channel = null;public static final String SFTP_REQ_HOST = "host";public static final String SFTP_REQ_PORT = "port";public static final String SFTP_REQ_USERNAME = "username";public static final String SFTP_REQ_PASSWORD = "password";public static final int SFTP_DEFAULT_PORT = 22;public static final String SFTP_REQ_LOC = "location";/*** 测试程序* @param arg* @throws Exception*/public static void main(String[] arg) throws Exception {// 设置主机ip,端口,用户名,密码Map<String, String> sftpDetails = new HashMap<String, String>();sftpDetails.put(SFTP_REQ_HOST, "10.180.137.221");sftpDetails.put(SFTP_REQ_USERNAME, "root");sftpDetails.put(SFTP_REQ_PASSWORD, "xxxx");sftpDetails.put(SFTP_REQ_PORT, "22");//测试文件上传String src = "C:\\xxx\\TMP\\site-1.10.4.zip"; // 本地文件名String dst = "/tmp/sftp/"; // 目标文件名uploadFile(src, dst, sftpDetails);//测试文件下载String srcFilename = "/tmp/sftp/site-1.10.4.zip";String dstFilename = "C:\\tmp\\site-1.10.4-new.zip";downloadFile(srcFilename, dstFilename, sftpDetails);}public static void downloadFile(String src, String dst,Map<String, String> sftpDetails) throws Exception {SftpUtil sftpUtil = new SftpUtil();ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 160000);// Retrieves the file attributes of a file or directory// SftpATTRS attr = chSftp.stat(src);// long fileSize = attr.getSize();//代码段1/代码段2/代码段3:分别演示了如何使用JSch的各种put方法来进行文件下载try {// 代码段1:使用这个方法时,dst可以是目录,若dst为目录,则下载到本地的文件名将与src文件名相同chSftp.get(src, dst, new MyProgressMonitor(),ChannelSftp.RESUME); //断点续传/***OutputStream out = new FileOutputStream(dst);// 代码段2:将目标服务器上文件名为src的文件下载到本地的一个输出流对象,该输出流为一个文件输出流chSftp.get(src, out, new MyProgressMonitor());// 代码段3:采用读取get方法返回的输入流数据的方式来下载文件InputStream is = chSftp.get(src, new MyProgressMonitor(),ChannelSftp.RESUME);byte[] buff = new byte[1024 * 2];int read;if (is != null) {do {read = is.read(buff, 0, buff.length);if (read > 0) {out.write(buff, 0, read);}out.flush();} while (read >= 0);}**/} catch (Exception e) {e.printStackTrace();} finally {chSftp.quit();sftpUtil.closeChannel();}}public static void uploadFile(String src, String dst,Map<String, String> sftpDetails) throws Exception {SftpUtil sftpUtil = new SftpUtil();ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 60000);/*** 代码段1/代码段2/代码段3分别演示了如何使用JSch的不同的put方法来进行文件上传。这三段代码实现的功能是一样的,* 都是将本地的文件src上传到了服务器的dst文件*//**代码段1OutputStream out = chSftp.put(dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块大小为256KBint read;if (out != null) {InputStream is = new FileInputStream(src);do {read = is.read(buff, 0, buff.length);if (read > 0) {out.write(buff, 0, read);}out.flush();} while (read >= 0);}**/// 使用这个方法时,dst可以是目录,当dst是目录时,上传后的目标文件名将与src文件名相同// ChannelSftp.RESUME:断点续传chSftp.put(src, dst, new MyProgressMonitor(), ChannelSftp.RESUME); // 代码段2// 将本地文件名为src的文件输入流上传到目标服务器,目标文件名为dst。// chSftp.put(new FileInputStream(src), dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 代码段3chSftp.quit();sftpUtil.closeChannel();}/*** 根据ip,用户名及密码得到一个SFTP* channel对象,即ChannelSftp的实例对象,在应用程序中就可以使用该对象来调用SFTP的各种操作方法** @param sftpDetails* @param timeout* @return* @throws JSchException*/public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout)throws JSchException {String ftpHost = sftpDetails.get(SFTP_REQ_HOST);String port = sftpDetails.get(SFTP_REQ_PORT);String ftpUserName = sftpDetails.get(SFTP_REQ_USERNAME);String ftpPassword = sftpDetails.get(SFTP_REQ_PASSWORD);int ftpPort = SFTP_DEFAULT_PORT;if (port != null && !port.equals("")) {ftpPort = Integer.valueOf(port);}JSch jsch = new JSch(); // 创建JSch对象session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根据用户名,主机ip,端口获取一个Session对象if (ftpPassword != null) {session.setPassword(ftpPassword); // 设置密码}Properties config = new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config); // 为Session对象设置propertiessession.setTimeout(timeout); // 设置timeout时间session.connect(5000); // 通过Session建立链接channel = session.openChannel("sftp"); // 打开SFTP通道channel.connect(); // 建立SFTP通道的连接return (ChannelSftp) channel;}public void closeChannel() throws Exception {if (channel != null) {channel.disconnect();}if (session != null) {session.disconnect();}}/*** 进度监控器-JSch每次传输一个数据块,就会调用count方法来实现主动进度通知**/public static class MyProgressMonitor implements SftpProgressMonitor {private long count = 0; //当前接收的总字节数private long max = 0; //最终文件大小private long percent = -1; //进度/*** 当每次传输了一个数据块后,调用count方法,count方法的参数为这一次传输的数据块大小*/@Overridepublic boolean count(long count) {this.count += count;if (percent >= this.count * 100 / max) {return true;}percent = this.count * 100 / max;System.out.println("Completed " + this.count + "(" + percent+ "%) out of " + max + ".");return true;}/*** 当传输结束时,调用end方法*/@Overridepublic void end() {System.out.println("Transferring done.");}/*** 当文件开始传输时,调用init方法*/@Overridepublic void init(int op, String src, String dest, long max) {if (op==SftpProgressMonitor.PUT) {System.out.println("Upload file begin.");}else {System.out.println("Download file begin.");}this.max = max;this.count = 0;this.percent = -1;}}/*** 官方提供的进度监控器**/public static class DemoProgressMonitor implements SftpProgressMonitor {ProgressMonitor monitor;long count = 0;long max = 0;/*** 当文件开始传输时,调用init方法。*/public void init(int op, String src, String dest, long max) {this.max = max;monitor = new ProgressMonitor(null,((op == SftpProgressMonitor.PUT) ? "put" : "get") + ": "+ src, "", 0, (int) max);count = 0;percent = -1;monitor.setProgress((int) this.count);monitor.setMillisToDecideToPopup(1000);}private long percent = -1;/*** 当每次传输了一个数据块后,调用count方法,count方法的参数为这一次传输的数据块大小。*/public boolean count(long count) {this.count += count;if (percent >= this.count * 100 / max) {return true;}percent = this.count * 100 / max;monitor.setNote("Completed " + this.count + "(" + percent+ "%) out of " + max + ".");monitor.setProgress((int) this.count);return !(monitor.isCanceled());}/*** 当传输结束时,调用end方法。*/public void end() {monitor.close();}}}
参考链接
【SFTP】使用Jsch实现Sftp文件下载-支持断点续传和进程监控的更多相关文章
- 【SFTP】使用Jsch实现Sftp文件上传-支持断点续传和进程监控
JSch是Java Secure Channel的缩写.JSch是一个SSH2的纯Java实现.它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,当然你也可以集成它的功能到 ...
- php大文件下载支持断点续传
<?php /** php下载类,支持断点续传 * * Func: * download: 下载文件 * setSpeed: 设置下载速度 * getRange: ...
- 使用JSch实现SFTP文件传输
1.JSch开发包下载 http://www.jcraft.com/jsch/ 目前最新版本为: jsch - 0.1.51 2.简单例子,列出指定目录下的文件列表 import java.util ...
- 基于JSch的Sftp工具类
本Sftp工具类的API如下所示. 1)构造方法摘要 Sftp(String host, int port, int timeout, String username, String password ...
- php 支持断点续传的文件下载类
php 支持断点续传的文件下载类 分类: php class2013-06-30 17:27 17748人阅读 评论(6) 收藏 举报 php断点续传下载http测试 php 支持断点续传,主要依靠H ...
- Java单线程文件下载,支持断点续传功能
前言: 程序下载文件时,有时会因为各种各样的原因下载中断,对于小文件来说影响不大,可以快速重新下载,但是下载大文件时,就会耗费很长时间,所以断点续传功能对于大文件很有必要. 文件下载的断点续传: 1. ...
- jsch连接sftp后连接未释放掉问题排查
项目中通过jsch中的sftp实现上传下载文件.在压测过程中,由于调用到sftp,下载文件不存在时,系统不断抛出异常,内存飙升,逐渐把swap区也占满,通过top监控未发现占用内存的进程,通过查找ss ...
- php实现的支持断点续传的文件下载类
通常来说,php支持断点续传,主要依靠HTTP协议中 header HTTP_RANGE实现. HTTP断点续传原理: Http头 Range.Content-Range()HTTP头中一般断点下载时 ...
- 【FTP】FTP文件上传下载-支持断点续传
Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...
随机推荐
- Uber优步宁波司机注册正式开始啦! UBER宁波司机注册指南!
自2012年Uber开始向全球进军以来,目前已进入全球56个国家和地区的市场,在全球超过270个城市提供服务, 而Uber公司的估值已高达412亿美元. [目前开通Uber优步叫车服务的中国城市] ...
- KBEngine 学习笔记
最近开始学习 KBE 扩展技能点>_<!所以建一个随笔记录一下遇到的小问题: 问题1 :DBMgr找不到LibMysql32.dll 解决:VS 中KBE源码 默认的是Win32 ,Win ...
- 估计PI——OpenCV&Cpp
来源:<Learning Image Processing With OpenCV> 算法原理:蒙特卡洛 PI的计算公式: Cpp代码: #include <opencv2/open ...
- ZendStudio13 PHP调试环境快速配置
1.百度ZendStudio13,汉化,破解,注册: 2.安装国产Apache+MySql一键安装环境phpStudy,方便快速 http://www.phpstudy.net/a.php/208. ...
- SILVERLIGHT 应急卫生模拟演练项目之childwindow
项目中经常要用到childwindow 默认SL提供的界面很不好看 也很难适应系统里的要求 单调的界面 木关系 可以我们可以通过BLEND自定义成我们想要的 首先新建立一个SILVERLIGHT 子窗 ...
- IONIC 开发的Android应用程序签名(或重新签名)详解
完全通过DOS命令来完成apk签名 给apk签名一共要用到3个工具,或者说3个命令,分别是:keytool.jarsigner和zipalign,下面是对这3个工具的简单介绍: ...
- BSD和云 – 不可错过的BSD聚会
自2012年开始,微软云计算与企业事业部和Citrix思杰,NetApp达成合作,共同开发出第一版针对Hyper-V虚拟设备驱动以及相关的用户态程序,并将此称之为集成服务 (Integration S ...
- CSS3 transition效果 360度旋转 旋转放大 放大 移动
效果一:360°旋转 修改rotate(旋转度数) * { transition:All 0.4s ease-in-out; -webkit-transition:All 0.4s ease-in-o ...
- python 使用virtualenvrapper虚拟环境管理工具
centos 默认安装的python是2.6版本的 使用virtualenv 环境管理工具建立python虚拟环境的时候会遇到一些错误,DEPRECATION: Python 2.6 is no lo ...
- 【 D3.js 入门系列 --- 7 】 理解 update, enter, exit 的使用
在前面几节中反复出现了如下代码: svg.selectAll("rect") .data(dataset) .enter() .append("rect") 当 ...