【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(); ...
随机推荐
- C#获得网卡信息 NetworkInterface IPInterfaceProperties
System.Net.NetworkInformation下的 1:NetworkInterface类,提供网络适配器的配置和统计信息. 可以通过它检测本机配置了多少网卡,哪些网络连接可用,获得网卡的 ...
- 必须掌握的八个cmd 命令
一,ping 它是用来检查网络是否通畅或者网络连接速度的命令.作为一个生活在网络上的管理员或者黑客来说,ping命令是第一个必须掌握的DOS命令,它 所利用的原理是这样的:网络上的机器都有唯一确定的I ...
- maven - 安装与配置
最近在了解maven的相关东西,在网上查了一些资料,现在简单整理一下. 一.maven 安装 1.先检查JDK ,Maven是一个java工具,所以请确保jdk环境已经正确安装在你的机器上. 2.点击 ...
- forEach遍历数组实例
forEach()取出数组中2的倍数和3的倍数的数 //for IE if(!Array.prototype.forEach){ Array.prototype.forEach = function( ...
- c51
ORG 0000HMOV R7,#08HMOV 83H,#01HMOV R4,#00HAA1:CLR P3.6 CLR P3.4 SETB P3.6 DJNZ R7,AA1AA2:JB P3.0,AA ...
- Lua IO库详解
I/O 库提供了两套不同风格的文件处理接口. 第一种风格使用隐式的文件句柄: 它提供设置默认输入文件及默认输出文件的操作, 所有的输入输出操作都针对这些默认文件. 第二种风格使用显式的文件句柄. 当使 ...
- Linux删除apt-get安装的软件
我们都知道安装软件最简单的方法是apt-get install,但是卸载就不常用了,如何卸载呢?1.sudo apt-get remove xxxxxsudo apt-get autoremove2. ...
- C#的提交表单方式主要有两种WebClient与HttpWebRequest
根据黄聪:C#模拟网站页面POST数据提交表单(转) using System; using System.Collections.Generic; using System.IO; using Sy ...
- bash while/until循环学习
while循环:条件满足,则循环:失败,则退出 如何退出? 必须有时刻,条件测试不成功 ? :条件控制变量 while 条件测试:do 循环体 done until循环:条件不满足,则循环:否则,退出 ...
- quick sort 的简化实现
Pivot 随机选取意义不大 第一种方法使用随机pivot,使得尽可能平均二分序列,而实际上一般来说需要排序的集合往往是乱序的,无需重新生成随机数作为pivot,大可使用固定位置的数作为pivot,这 ...