【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(); ...
随机推荐
- PAT 1072. Gas Station (30)
A gas station has to be built at such a location that the minimum distance between the station and a ...
- 安装MySql for Visual Studio后,打开IDE找不到MySql选项
只能说安装程序功能不健全,找不到Visual Studio也不问,自己随便找了个地儿把插件放下了...这程序员真2! 原文在这里,作者思路对头.原文:"安装MySql for Visual ...
- How to connect to Linux VM from Windows
- libc++
今天测试最新的微信iOS SDK, 仅仅是建了一个空的工程,把sdk加进去运行,就报了以下错误: Undefined symbols for architecture x86_64: "op ...
- 原创: How to build a query based on Definition Updates installed
In SCCM 2012 R2, you can use following class. Use SMS_CombinedDeviceResources.EPAntivirusSignatureLa ...
- bash 取文件特定行
比如,想要取某文件10-20行 可以用sed sed -n '10,20p' XXX.txt 非常方便!
- Android倒计时:计算两个时间将得到的时间差转化为倒计时(xx时xx分xx秒格式)
首先是一个自定义控件: public class RushBuyCountDownTimerView extends LinearLayout { // 小时,十位 private TextView ...
- 集合视图 UICollectionView
什么是UICollectionView UICollectionView是一种新的数据展示方式,简单来说可以把他理解成多列的UITableView(请一定注意这是UICollectionView的最最 ...
- eclipse修改web项目部署路径
Eclipse中用Tomcat发布的Web项目,更改其部署路径 我的Eclipse的工作目录是D:/workspace 先配置Tomcat 选择你的tomcat版本 点击next 这里先不要把项目添加 ...
- sublime 中文乱码
一.安装Package Control 使用Sublime Text2首先就要安装Package Control,这样就能使用丰富的插件包了 (1)访问Package Control站点按照提示复 ...