FTP上传下载使用java(JSch技术)

apache commons net 对FTP上传下载很好,但有个致命缺点。它天生不支持SFTP协议。然而现在很多FTP服务器都是SFTP协议。所以就不能在common-net的API了。

使用JSch(但是它的API没有common-net丰富)。

Jsch简单使用 SFTP上传下载:

1.下载jsch依赖的jar,具体可以百度。

2.上传

JSch jsch = new JSch(); // 创建JSch对象
Session session = jsch.getSession("ftp用户名", "IP", 端口);
session.setPassword(ftpUserPwd);
session.setConfig("StrictHostKeyChecking","no"); // 为Session对象设置properties
session.setTimeout(10000); // 设置timeout时间
session.connect(); // 通过Session建立链接
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
//channel.cd(ftpFileDir);//进入FTP的某个目录
try{
	channel.cd(dirs[i]);//目录不存在会报异常
}catch (SftpException e) {
	if(channel.SSH_FX_NO_SUCH_FILE == e.id){ //表示目录不存在
		channel.mkdir(dirs[i]);
		channel.cd(dirs[i]);
	}
}
channel.put(srcFile, targFile, ChannelSftp.OVERWRITE);//上传
//记得关闭连接
channel.quit();
channel.disconnect();
session.close();

3.下载:

ByteArrayOutputStream outArr = null;
ChannelSftp channel = null;
try {
	outArr = new ByteArrayOutputStream();
	channel = (ChannelSftp) session.openChannel("sftp");
	channel.connect(); // 建立SFTP通道的连接
	channel.get(src, outArr);
} catch (Exception e) {
	e.printStackTrace();
	throw new Exception(e);
}finally{
	channel.quit();
	channel.disconnect();
}
return outArr;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值