【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(); ...
随机推荐
- 【搬砖】【Python数据分析】Pycharm中plot绘图不能显示出来
最近在看<Python数据分析>这本书,而自己写代码一直用的是Pycharm,在练习的时候就碰到了plot()绘图不能显示出来的问题.网上翻了一下找到知乎上一篇回答,试了一下好像不行,而且 ...
- [驱动开发] windbg符号表
新建"环境变量 - 系统":_NT_SYMBOL_PATH 值为:SRV*FullDirPath*http://msdl.microsoft.com/download/symbol ...
- RoR简单的应用程序
在dos环境下执行找到需要新建的项目路径 输入命令rails -v #查看版本号
- test latex1
equation systems: \begin{equation} 1 + 2 = 3 \ 1 = 3 - 2 \end{equation} align text \begin{align} 1+2 ...
- Mono.Android 基础
Mono.Android 基础 (地址) Mono.Android项目结构是 — Project + Assets + Resources + drawable + layout + values R ...
- powerdesigner 生成mysql PDM 的COMMENT注释
1powerdesigner 生成mysql PDM 的COMMENT注释 默认的pd没有生成注释,针对mysql5.0可以如下修改.在Database-->edit Current DBMS. ...
- 深入理解Javascript中this, prototype, constructor
在Javascript面向对象编程中经常需要使用到this,prototype和constructor这3个关键字. 1.首先介绍一下this的使用:this表示当前对象;如果在全局中使用this,则 ...
- c语言结构体&常指针和常量指针的区别
结构体: 关系密切但数据类型不尽相同, 常指针和常量指针的区别: char * const cp : 定义一个指向字符的指针常数,即const指针,常指针. const char* p : 定义一个指 ...
- drozer安装之夜深模拟器
首先下载drozer的安装包 可以直接到官网下载:https://labs.mwrinfosecurity.com/tools/drozer/ 安装 解压压缩包其中 setup.exe 为Win ...
- 【转】 TechED2010与我(三) —— 初识云计算
作者用到的比喻很好. 网址:TechED2010与我(三) -- 初识云计算 初识云计算最近"云计算"被炒的很热,但是由于工作重点主要是做WinForm的控件开发,对云计算的接触比 ...