java sftp jsch_JSch - Java实现的SFTP(文件上传详解篇)

packagecom.longyg.sftp;public classSFTPConstants {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";

}

文件上传

实现文件上传可以调用ChannelSftp对象的put方法。ChannelSftp中有12个put方法的重载方法:

public void put(String src, String dst)

将本地文件名为src的文件上传到目标服务器,目标文件名为dst,若dst为目录,则目标文件名将与src文件名相同。

采用默认的传输模式:OVERWRITE

public void put(String src, String dst, int mode)

将本地文件名为src的文件上传到目标服务器,目标文件名为dst,若dst为目录,则目标文件名将与src文件名相同。

指定文件传输模式为mode(mode可选值为:ChannelSftp.OVERWRITE,ChannelSftp.RESUME,

ChannelSftp.APPEND)

public void put(String src, String dst, SftpProgressMonitor monitor)

将本地文件名为src的文件上传到目标服务器,目标文件名为dst,若dst为目录,则目标文件名将与src文件名相同。

采用默认的传输模式:OVERWRITE

并使用实现了SftpProgressMonitor接口的monitor对象来监控文件传输的进度。

public void put(String src, String dst,

SftpProgressMonitor monitor, int mode)

将本地文件名为src的文件上传到目标服务器,目标文件名为dst,若dst为目录,则目标文件名将与src文件名相同。

指定传输模式为mode

并使用实现了SftpProgressMonitor接口的monitor对象来监控文件传输的进度。

public void put(InputStream src, String dst)

将本地的input stream对象src上传到目标服务器,目标文件名为dst,dst不能为目录。

采用默认的传输模式:OVERWRITE

public void put(InputStream src, String dst, int mode)

将本地的input stream对象src上传到目标服务器,目标文件名为dst,dst不能为目录。

指定文件传输模式为mode

public void put(InputStream src, String dst, SftpProgressMonitor monitor)

将本地的input stream对象src上传到目标服务器,目标文件名为dst,dst不能为目录。

采用默认的传输模式:OVERWRITE

并使用实现了SftpProgressMonitor接口的monitor对象来监控传输的进度。

public void put(InputStream src, String dst,

SftpProgressMonitor monitor, int mode)

将本地的input stream对象src上传到目标服务器,目标文件名为dst,dst不能为目录。

指定文件传输模式为mode

并使用实现了SftpProgressMonitor接口的monitor对象来监控传输的进度。

public OutputStream put(String dst)

该方法返回一个输出流,可以向该输出流中写入数据,最终将数据传输到目标服务器,目标文件名为dst,dst不能为目录。

采用默认的传输模式:OVERWRITE

public OutputStream put(String dst, final int mode)

该方法返回一个输出流,可以向该输出流中写入数据,最终将数据传输到目标服务器,目标文件名为dst,dst不能为目录。

指定文件传输模式为mode

public OutputStream put(String dst, final SftpProgressMonitor monitor, final int mode)

该方法返回一个输出流,可以向该输出流中写入数据,最终将数据传输到目标服务器,目标文件名为dst,dst不能为目录。

指定文件传输模式为mode

并使用实现了SftpProgressMonitor接口的monitor对象来监控传输的进度。

public OutputStream put(String dst, final SftpProgressMonitor monitor, final int mode, long offset)

该方法返回一个输出流,可以向该输出流中写入数据,最终将数据传输到目标服务器,目标文件名为dst,dst不能为目录。

指定文件传输模式为mode

并使用实现了SftpProgressMonitor接口的monitor对象来监控传输的进度。

offset指定了一个偏移量,从输出流偏移offset开始写入数据。

应用实例:

SFTPTest.java

packagecom.longyg.sftp;importjava.util.HashMap;importjava.util.Map;importcom.jcraft.jsch.ChannelSftp;public classSFTPTest {publicSFTPChannel getSFTPChannel() {return newSFTPChannel();

}/***@paramargs

*@throwsException*/

public static void main(String[] args) throwsException {

SFTPTest test= newSFTPTest();

Map sftpDetails = new HashMap();//设置主机ip,端口,用户名,密码

sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "10.9.167.55");

sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME,"root");

sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD,"arthur");

sftpDetails.put(SFTPConstants.SFTP_REQ_PORT,"22");

String src= "D:\\DevSoft\\HB-SnagIt1001.rar"; //本地文件名

String dst = "/home/omc/ylong/sftp/HB-SnagIt1001.rar"; //目标文件名

SFTPChannel channel=test.getSFTPChannel();

ChannelSftp chSftp= channel.getChannel(sftpDetails, 60000);/*** 代码段1

OutputStream out = chSftp.put(dst, ChannelSftp.OVERWRITE); // 使用OVERWRITE模式

byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块大小为256KB

int read;

if (out != null) {

System.out.println("Start to read input stream");

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);

System.out.println("input stream read done.");

}

**/chSftp.put(src, dst, ChannelSftp.OVERWRITE);//代码段2//chSftp.put(new FileInputStream(src), dst, ChannelSftp.OVERWRITE);//代码段3

chSftp.quit();

channel.closeChannel();

}

}

注:请分别将代码段1,代码段2,代码段3取消注释,运行程序来进行测试。这三段代码分别演示了如何使用JSch的不同的put方法来进行文件上传。

代码段1:采用向put方法返回的输出流中写入数据的方式来传输文件。 需要由程序来决定写入什么样的数据,这里是将本地文件的输入流写入输出流。采用这种方式的好处是,可以自行设定每次写入输出流的数据块大小,如本示例中的语句:

byte[] buff = new byte[1024 * 256]; //设定每次传输的数据块大小为256KB

代码段2:直接将本地文件名为src的文件上传到目标服务器,目标文件名为dst。(注:使用这个方法时,dst可以是目录,当dst是目录时,上传后的目标文件名将与src文件名相同)

代码段3:将本地文件名为src的文件输入流上传到目标服务器,目标文件名为dst。

这三段代码实现的功能是一样的,都是将本地的文件src上传到了服务器的dst文件。使用时可根据具体情况选择使用哪种实现方式。

监控传输进度

从前面的介绍中知道,JSch支持在文件传输时对传输进度的监控。可以实现JSch提供的SftpProgressMonitor接口来完成这个功能。

SftpProgressMonitor接口类的定义为:

packagecom.jcraft.jsch;public interfaceSftpProgressMonitor{public static final int PUT=0;public static final int GET=1;void init(int op, String src, String dest, longmax);boolean count(longcount);voidend();

}

init(): 当文件开始传输时,调用init方法。

count(): 当每次传输了一个数据块后,调用count方法,count方法的参数为这一次传输的数据块大小。

end(): 当传输结束时,调用end方法。

下面是一个简单的实现:

MyProgressMonitor.java

packagecom.longyg.sftp;importcom.jcraft.jsch.SftpProgressMonitor;public class MyProgressMonitor implementsSftpProgressMonitor {private longtransfered;

@Overridepublic boolean count(longcount) {

transfered= transfered +count;

System.out.println("Currently transferred total size: " + transfered + " bytes");return true;

}

@Overridepublic voidend() {

System.out.println("Transferring done.");

}

@Overridepublic void init(int op, String src, String dest, longmax) {

System.out.println("Transferring begin.");

}

}

此时如果改变SFTPTest main方法里调用的put方法,即可实现监控传输进度:

SFTPTest.java

packagecom.longyg.sftp;importjava.util.HashMap;importjava.util.Map;importcom.jcraft.jsch.ChannelSftp;public classSFTPTest {publicSFTPChannel getSFTPChannel() {return newSFTPChannel();

}/***@paramargs

*@throwsException*/

public static void main(String[] args) throwsException {

SFTPTest test= newSFTPTest();

Map sftpDetails = new HashMap();//设置主机ip,端口,用户名,密码

sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "10.9.167.55");

sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME,"root");

sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD,"arthur");

sftpDetails.put(SFTPConstants.SFTP_REQ_PORT,"22");

String src= "D:\\DevSoft\\HB-SnagIt1001.rar"; //本地文件名

String dst = "/home/omc/ylong/sftp/HB-SnagIt1001.rar"; //目标文件名

SFTPChannel channel=test.getSFTPChannel();

ChannelSftp chSftp= channel.getChannel(sftpDetails, 60000);/*** 代码段1

OutputStream out = chSftp.put(dst, new MyProgressMonitor(), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式

byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块大小为256KB

int read;

if (out != null) {

System.out.println("Start to read input stream");

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);

System.out.println("input stream read done.");

}

**/chSftp.put(src, dst,new MyProgressMonitor(), ChannelSftp.OVERWRITE); //代码段2//chSftp.put(new FileInputStream(src), dst, new MyProgressMonitor(), ChannelSftp.OVERWRITE);//代码段3

chSftp.quit();

channel.closeChannel();

}

}

注意修改的内容仅仅是put方法,在put方法中增加了SftpProgressMonitor的实现类对象monitor作为参数,即添加了对进度监控的支持。

运行,输出结果如下:

Start to read input stream

Currently transferred total size:262144bytes

Currently transferred total size:524288bytes

Currently transferred total size:786432bytes

Currently transferred total size:1048576bytes

Currently transferred total size:1310720bytes

Currently transferred total size:1572864bytes

Currently transferred total size:1835008bytes

Currently transferred total size:2097152bytes

Currently transferred total size:2359296bytes

Currently transferred total size:2621440bytes

Currently transferred total size:2883584bytes

Currently transferred total size:3145728bytes

Currently transferred total size:3407872bytes

Currently transferred total size:3670016bytes

Currently transferred total size:3848374bytes

input stream read done.

当然这个SftpProgressMonitor的实现实在太简单。JSch每次传输一个数据块,就会调用count方法来实现主动进度通知。

现在我们希望每间隔一定的时间才获取一下文件传输的进度。。。看看下面的SftpProgressMonitor实现:

packagecom.longyg.sftp;importjava.text.DecimalFormat;importjava.util.Timer;importjava.util.TimerTask;importcom.jcraft.jsch.SftpProgressMonitor;public class FileProgressMonitor extends TimerTask implementsSftpProgressMonitor {private long progressInterval = 5 * 1000; //默认间隔时间为5秒

private boolean isEnd = false; //记录传输是否结束

private long transfered; //记录已传输的数据总大小

private long fileSize; //记录文件总大小

private Timer timer; //定时器对象

private boolean isScheduled = false; //记录是否已启动timer记时器

public FileProgressMonitor(longfileSize) {this.fileSize =fileSize;

}

@Overridepublic voidrun() {if (!isEnd()) { //判断传输是否已结束

System.out.println("Transfering is in progress.");long transfered =getTransfered();if (transfered != fileSize) { //判断当前已传输数据大小是否等于文件总大小

System.out.println("Current transfered: " + transfered + " bytes");

sendProgressMessage(transfered);

}else{

System.out.println("File transfering is done.");

setEnd(true); //如果当前已传输数据大小等于文件总大小,说明已完成,设置end

}

}else{

System.out.println("Transfering done. Cancel timer.");

stop();//如果传输结束,停止timer记时器

return;

}

}public voidstop() {

System.out.println("Try to stop progress monitor.");if (timer != null) {

timer.cancel();

timer.purge();

timer= null;

isScheduled= false;

}

System.out.println("Progress monitor stoped.");

}public voidstart() {

System.out.println("Try to start progress monitor.");if (timer == null) {

timer= newTimer();

}

timer.schedule(this, 1000, progressInterval);

isScheduled= true;

System.out.println("Progress monitor started.");

}/*** 打印progress信息

*@paramtransfered*/

private void sendProgressMessage(longtransfered) {if (fileSize != 0) {double d = ((double)transfered * 100)/(double)fileSize;

DecimalFormat df= new DecimalFormat( "#.##");

System.out.println("Sending progress message: " + df.format(d) + "%");

}else{

System.out.println("Sending progress message: " +transfered);

}

}/*** 实现了SftpProgressMonitor接口的count方法*/

public boolean count(longcount) {if (isEnd()) return false;if (!isScheduled) {

start();

}

add(count);return true;

}/*** 实现了SftpProgressMonitor接口的end方法*/

public voidend() {

setEnd(true);

System.out.println("transfering end.");

}private synchronized void add(longcount) {

transfered= transfered +count;

}private synchronized longgetTransfered() {returntransfered;

}public synchronized void setTransfered(longtransfered) {this.transfered =transfered;

}private synchronized void setEnd(booleanisEnd) {this.isEnd =isEnd;

}private synchronized booleanisEnd() {returnisEnd;

}public void init(int op, String src, String dest, longmax) {//Not used for putting InputStream

}

}

再次修改SFTPTest main方法里的put方法,改为使用新的SftpProgressMonitor的实现类对象monitor作为参数,注意新的monitor对象的构造函数需要传入文件大小作为参数:

packagecom.longyg.sftp;importjava.io.File;importjava.util.HashMap;importjava.util.Map;importcom.jcraft.jsch.ChannelSftp;public classSFTPTest {publicSFTPChannel getSFTPChannel() {return newSFTPChannel();

}/***@paramargs

*@throwsException*/

public static void main(String[] args) throwsException {

SFTPTest test= newSFTPTest();

Map sftpDetails = new HashMap();//设置主机ip,端口,用户名,密码

sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "10.9.167.55");

sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME,"root");

sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD,"arthur");

sftpDetails.put(SFTPConstants.SFTP_REQ_PORT,"22");

String src= "D:\\DevSoft\\HB-SnagIt1001.rar"; //本地文件名

String dst = "/home/omc/ylong/sftp/HB-SnagIt1001.rar"; //目标文件名

SFTPChannel channel=test.getSFTPChannel();

ChannelSftp chSftp= channel.getChannel(sftpDetails, 60000);

File file= newFile(src);long fileSize =file.length();/*** 代码段1

OutputStream out = chSftp.put(dst, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式

byte[] buff = new byte[1024 * 256]; // 设定每次传输的数据块大小为256KB

int read;

if (out != null) {

System.out.println("Start to read input stream");

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);

System.out.println("input stream read done.");

}

**/chSftp.put(src, dst,new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE); //代码段2//chSftp.put(new FileInputStream(src), dst, new FileProgressMonitor(fileSize), ChannelSftp.OVERWRITE);//代码段3

chSftp.quit();

channel.closeChannel();

}

}

再次运行,结果输出为:

Try to start progress monitor.

Progress monitor started.

Transfering is in progress.

Current transfered:98019bytes

Sending progress message:2.55%Transfering is in progress.

Current transfered:751479bytes

Sending progress message:19.53%Transfering is in progress.

Current transfered:1078209bytes

Sending progress message:28.02%......

Transfering is in progress.

Current transfered:3430665bytes

Sending progress message:89.15%transfering end.

Transfering done. Cancel timer.

Try to stop progress monitor.

Progress monitor stoped.

现在,程序每隔5秒钟才会打印一下进度信息。可以修改FileProgressMonitor类里的progressInterval变量的值,来修改默认的间隔时间。

本文转自:http://www.cnblogs.com/longyg/archive/2012/06/25/2556576.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值