【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文件
*/
/**代码段1
OutputStream out = chSftp.put(dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式
byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块大小为256KB
int 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); // 代码段3
chSftp.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对象设置properties
session.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方法的参数为这一次传输的数据块大小
*/
@Override
public 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方法
*/
@Override
public void end() {
System.out.println("Transferring done.");
}
/**
* 当文件开始传输时,调用init方法
*/
@Override
public 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(); ...
随机推荐
- iOS多线程学习及总结
能有份网上的存储资料,备以后提升及参考 iOS 多线程编程 简介 一. iOS有三种多线程编程的技术,分别是: 1. NSThread 2. Cocoa NSOp ...
- 路线更改事件 $routeChangeStart 与 $locationChangeStart
$routeChangeStart属于$route模块,使用将要改变的路由和当前路由对比,在没有跳转之前 参数包括 function(event, next, current) next $loca ...
- 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 ...
- CentOS下查看进程和删除进程
1. 在 LINUX 命令平台输入 1-2 个字符后按 Tab 键会自动补全后面的部分(前提是要有这个东西,例如在装了 tomcat 的前提下, 输入 tomcat 的 to 按 tab).2. ps ...
- matlab中的数据结构
一.cell 1. function: num2cell(A,n) n表示如何把A中的数据转换为cell. n=1表示把每列的所有行转换为cell:n=2表示把每行的所有列转换为cell. >& ...
- PR视屏剪切
一款常用的视频编辑软件,由Adobe公司推出.现在常用的有CS4.CS5.CS6.CC.CC 2014及CC 2015版本.是一款编辑画面质量比较好的软件,有较好的兼容性,且可以与Adobe公司推出的 ...
- zenefits oa - random(5) to generate a random(7)
If given a function that generates a random number from 1 to 5, how do you use this function to gene ...
- linux驱动之触摸屏驱动程序
触摸屏归纳为输入子系统,这里主要是针对电阻屏,其使用过程如下 :当用触摸笔按下时,产生中断.在中断处理函数处理函数中启动ADC转换x,y坐标.ADC结束,产生ADC中断,在ADC中断处理函数里上报(i ...
- LPTHW 笨办法学python 40章 类
今天读了LPTHW的第40章以后豁然开朗,原来一直愚钝,不太理解类的定义和使用,还有就是不太理解关于self的定义. class MyStuff(object): def __init__(self) ...
- [c++] vector的使用
} { vec.push_back(value); } { vector< vector<,); vector<, sec ...