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

- 根据Jsch创建Session;
- 设置Session密码、超时时间和属性等;
- 连接session;
- 使用Session创建ChannelSftp通道;
- 接下来就可以使用ChannelSftp进行各种操作了:如文件上传、文件下载;
- 最后,关系各种资源:如Session、ChannelSftp等;
创建ChannelSftp对象

监控传输进度
文件上传

测试断点续传



完整程序
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.text.DecimalFormat;import java.util.HashMap;import java.util.Map;import java.util.Properties;import java.util.Timer;import java.util.TimerTask;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, "xxx");sftpDetails.put(SFTP_REQ_PORT, "22");//测试文件上传String src = "C:\\xxx\\TMP\\site-1.10.4.zip"; // 本地文件名String dst = "/tmp/sftp/"; // 目标文件名uploadFile(src, dst, sftpDetails);}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) {System.out.println("Transferring 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文件上传-支持断点续传和进程监控的更多相关文章
- FTP文件上传 支持断点续传 并 打印下载进度(二) —— 单线程实现
这个就看代码,哈哈哈哈哈 需要用到的jar包是: <dependency> <groupId>commons-net</groupId> <artifact ...
- 【SFTP】使用Jsch实现Sftp文件下载-支持断点续传和进程监控
参考上篇文章: <[SFTP]使用Jsch实现Sftp文件下载-支持断点续传和进程监控>:http://www.cnblogs.com/ssslinppp/p/6248763.html ...
- skymvc文件上传支持多文件上传
skymvc文件上传支持多文件上传 支持单文件.多文件上传 可以设定 文件大小.存储目录.文件类型 //上传的文件目录 $this->upload->uploaddir="att ...
- .net core版 文件上传/ 支持批量上传,拖拽以及预览,bootstrap fileinput上传文件
asp.net mvc请移步 mvc文件上传支持批量上传,拖拽以及预览,文件内容校验 本篇内容主要解决.net core中文件上传的问题 开发环境:ubuntu+vscode 1.导入所需要的包:n ...
- 4GB以上超大文件上传和断点续传服务器的实现
随着视频网站和大数据应用的普及,特别是高清视频和4K视频应用的到来,超大文件上传已经成为了日常的基础应用需求. 但是在很多情况下,平台运营方并没有大文件上传和断点续传的开发经验,往往在网上找一些简单的 ...
- mvc文件上传支持批量上传,拖拽以及预览,文件内容校验等
使用bootstrap-fileinput 使用方式: 1.nuget:Install-Package bootstrap-fileinput 2.语言本地化{下载fileinput_locale_z ...
- PHP实现阿里云OSS文件上传(支持批量)
上传文件至阿里云OSS,整体逻辑是,文件先临时上传到本地,然后在上传到OSS,最后删除本地的临时文件(也可以不删,具体看自己的业务需求),具体实现流程如下: 1.下载阿里云OSS对象上传SDK(P ...
- php大文件上传支持断点上传
文件夹数据库处理逻辑 publicclass DbFolder { JSONObject root; public DbFolder() { this.root = new JSONObject(); ...
- asp.net mvc大文件上传、断点续传功能。
文件夹数据库处理逻辑 publicclass DbFolder { JSONObject root; public DbFolder() { this.root = new JSONObject(); ...
随机推荐
- SQlServer第一天
SQLserver是个什么东西?相当于一是个货仓,在计算机领域的货仓,学名:数据库. 数据库是个什么东西呢?是指长期存储在计算机内的.有组织.可共享的数据结合.由此可知数据库的三个特点:永久存储.有组 ...
- 华为交换机sflow配置
华为交换机sflow功能配置 1.配置交换机的sflow流发送 [系统视图]sflow agen ip x.x.x.x 设置sflow输出源 [系统视图]sflow ...
- HDU4010 (动态树)
Problem Query on The Trees 题目大意 给一棵树,有点权,要求维护4种操作. 操作1:加一条边. 操作2:删一条边. 操作3:将一条路径上的点权增加w. 操作4:询问一条路径上 ...
- 第六周——分析Linux内核创建一个新进程的过程
"万子恵 + 原创作品转载请注明出处 + <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 &q ...
- Windows 10和Visual Studio 2015 能给.Net方向的开发从业者带来什么?
.Net 多年前我们选择了你,现在在当前的移动互联网热火朝天的时代,你能给我们什么样的惊喜?面对IOS和android的势头,windows的移动端能否实现三国鼎立? windows 10 号称统一各 ...
- 用ajax提交form表单及乱码问题
要求 1. form里是习题和选择的答案包含内容较多,直接用ajax获取页面元素较多,麻烦. 2. 也不能直接用form提交,form提交后会跳转页面,如果出错想在本页面获取错误信息(ajax提交)且 ...
- http学习 1-3 chapter3-报文
如果说HTTP是因特网的信使,那么HTTP报文就是它用来搬东西的包裹了. 报文是如何流动的. HTTP报文的三个组成部分(起始行.首部和实体的主体部分) 请求和响应报文之间的区别 请求报文支持的各种功 ...
- 用sql语句建表
CREATE TABLE USER (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(30) NOT NULL, p ...
- Codeforces Round #284 (Div. 2)A B C 模拟 数学
A. Watching a movie time limit per test 1 second memory limit per test 256 megabytes input standard ...
- (转) Spring框架笔记(二十五)——NamedParameterJdbcTemplate与具名参数(转)
在经典的 JDBC 用法中, SQL 参数是用占位符 ? 表示,并且受到位置的限制. 定位参数的问题在于, 一旦参数的顺序发生变化, 就必须改变参数绑定. 在 Spring JDBC 框架中, 绑定 ...