Java SFTP 上传、下载等操作
ninehua 2024-11-17 19:51 102 浏览
Java SFTP 上传、下载等操作
实际开发中用到了 SFTP
用于交换批量数据文件,然后琢磨了下这方面的东西,基于 JSch
写了个工具类记录下,便于日后使用。
JSch
是 SSH2
的纯Java实现。JSch
可以连接到sshd服务器并使用端口转发,X11转发,文件传输等,并且很方便的将其功能集成到Java程序中。
1、添加依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2、SFTPUtils 工具类
public class SFTPUtils {
private Logger log = LoggerFactory.getLogger(SFTPUtils.class);
private String host; // 主机名称/IP
private int port = 22; // 端口
private String username; // 用户名
private String password; // 密码
private ChannelSftp sftp = null;
private Channel channel = null;
private Session session = null;
public SFTPUtils(String host, String userName, String password) {
this.host = host;
this.username = userName;
this.password = password;
}
public SFTPUtils(String host, int port, String userName, String password) {
this.host = host;
this.port = port;
this.username = userName;
this.password = password;
}
/**
* 连接SFTP服务器
*
* @throws JSchException
*/
public void connect() throws JSchException {
JSch jSch = new JSch();
session = jSch.getSession(username, host, port);
session.setPassword(password);
session.setConfig(this.buildConfig());
session.connect();
channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
log.info("连接主机:{} 登录成功", host);
}
/**
* 构建连接配置参数
*
* @return Properties
*/
private Properties buildConfig() {
Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no");
return properties;
}
/**
* 关闭连接
*/
public void disconnect() {
try {
if (sftp.isConnected()) {
sftp.disconnect();
}
if (channel.isConnected()) {
channel.disconnect();
}
if (session.isConnected()) {
session.disconnect();
}
} catch (Throwable e) {
//ignore
}
}
/**
* 下载文件
*
* @param sftpPath 服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
* 例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
* 指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
* @param fileName 文件名
* @param toFilePath 下载保存文件路径,路径+文件名,例如:d:/test.txt
* @return
*/
public boolean downloadFile(String sftpPath, String fileName, String toFilePath) {
FileOutputStream fileOutputStream = null;
try {
if (StringUtils.isNotBlank(sftpPath)) {
sftp.cd(sftpPath);
}
fileOutputStream = new FileOutputStream(new File(toFilePath));
sftp.get(fileName, fileOutputStream);
return true;
} catch (Exception e) {
log.error("下载文件错误", e);
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
//ignore
}
}
}
return false;
}
/**
* 上传文件
*
* @param sftpPath 服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
* 例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
* 指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
* @param fileName 上传后文件名
* @param localFilePath 文件路径,路径+文件名,例如:d:/test.txt
* @return
*/
public boolean uploadFile(String sftpPath, String fileName, String localFilePath) {
FileInputStream inputStream = null;
try {
if (StringUtils.isNotBlank(sftpPath)) {
sftp.cd(sftpPath);
}
inputStream = new FileInputStream(new File(localFilePath));
sftp.put(inputStream, fileName);
return true;
} catch (Exception e) {
log.error("上传文件错误", e);
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
//ignore
}
}
}
return false;
}
/**
* 上传文件
*
* @param sftpPath 服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
* 例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
* 指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
* @param fileName 上传后文件名
* @param inputStream 文件输入流
* @return
*/
public boolean uploadFile(String sftpPath, String fileName, InputStream inputStream) {
try {
if (StringUtils.isNotBlank(sftpPath)) {
sftp.cd(sftpPath);
}
sftp.put(inputStream, fileName);
return true;
} catch (Exception e) {
log.error("上传文件错误", e);
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
//ignore
}
}
}
return false;
}
/**
* 删除文件
*
* @param sftpPath 服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
* 例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
* 指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
* @param fileName 文件名
* @return
*/
public boolean deleteFile(String sftpPath, String fileName) {
try {
if (StringUtils.isNotBlank(sftpPath)) {
sftp.cd(sftpPath);
}
sftp.rm(fileName);
return true;
} catch (Exception e) {
log.error("删除文件失败", e);
}
return false;
}
/**
* 查询指定目录下信息
*
* @param sftpPath 服务器路径,不指定路径默认是FTP的根路径,指定路径是指的SFTP的根路径下开始。
* 例如:SFTP根路径为:/sftp/file,那么默认下载文件会去根路径下载,而指定 sftpPath 也是从根路径下开始;
* 指定 sftpPath 为 word,那么是从 /sftp/file/word 路径中查找文件下载。为空表示忽略该参数。
* @return
*/
public List<String> listFiles(String sftpPath) throws SftpException {
Vector files = sftp.ls(sftpPath);
List<String> result = new ArrayList<String>();
Iterator iterator = files.iterator();
while (iterator.hasNext()) {
LsEntry isEntity = (LsEntry) iterator.next();
result.add(isEntity.getFilename());
}
return result;
}
}
在使用的的时候,需要调用 connect()
开启连接,使用完后调用 disconnect()
关闭连接 。
jsch
官方的文档说明 http://www.jcraft.com/jsch/
本文主要用于个人记录笔记!
相关推荐
- 让Mac也能读取Android设备文件(mac系统能读取win的文件么)
-
由于苹果的iOS和谷歌的Android系统属于竞争关系,因此苹果的电脑系统MacOSX并不支持MTP协议,这就使得通过USB将Android设备连接到Mac电脑上无法识别,更别说读取里面的文件了。...
- 抛弃Windows吧!谷歌推免费Chrome系统,一个U盘就搞定
-
在目前的个人电脑上,最主流的系统当然是Windows,不过除了Windows之外,我们也可以选择购买苹果的电脑,使用苹果的MacOS系统。不过除了苹果和微软的系统之外,实际上谷歌也有自己用于个人电脑...
- 安卓版Apple Music应用正式上架Google Play
-
IT之家讯11月11日消息,苹果今天正式推出了安卓版AppleMusic应用(测试版),用户可在谷歌应用商店GooglePlay进行下载。AppleMusic最初只提供给Mac、iPhone和...
- Mac 基于HTTP方式访问下载共享文件,配置共享服务器
-
方法一:使用Python的SimpleHTTPServer进行局域网文件共享Mac自带Python,所以不需要安装其他软件,一条命令即可1):进入需要共享的文件夹,如Public文件夹cd/Us...
- 谷歌 Gmail 现可设置为 iOS 14/iPadOS 14 默认邮件应用
-
IT之家9月22日消息据外媒MacRumors报道,苹果iOS14与iPadOS14允许用户将第三方应用设置为iPhone和iPad的默认浏览器应用。目前,用户还可以将第三方...
- 终于免费了!谷歌地球专业版下载(谷歌地球专业版多少钱)
-
IT之家(www.ithome.com):终于免费了!谷歌地球专业版下载IT之家讯1月31日消息,谷歌地球专业版GoogleEarthPro现在完全免费了。在此之前,要使用这款专业版的谷歌地球需要...
- 谷歌计划将于11月发布64位Mac版Chrome
-
投稿by:hnn072来源:威锋网PostTime:2014-09-1523:51:55以下为文章全文:威锋网9月15日消息,日前,谷歌公司在官方博客中正式宣布,谷歌将在今年11月发布的...
- Google首次推出beta版的64位Mac Chrome浏览器
-
在宣布Windows版的64位Chrome进入稳定版(Chrome37)2天之后,Google刚刚又发布38版的Chromebeta版,除了增加新的用户档案切换界面并引入G...
- YouTube应用下载全攻略:安卓、iOS及视频下载指南
-
#哪些网站帮你打开了新世界的大门?#YouTube是全球最大的视频分享平台,拥有数十亿用户。它允许用户上传、分享和观看视频,涵盖娱乐、教育、新闻、音乐、博客、游戏等各类视频。通常,您可以使用You...
- MaterialDesign来袭!iOS谷歌浏览器更新!
-
今日,谷歌发布了最新的iOS版Chrome浏览器应用升级,在新版本中该应用添加了最新的MaterialDesign界面,并增加了在iOS设备和Mac中快速无缝切换浏览内容的Handoff特性支持。最...
- 谷歌为Canary/Dev分支Mac版Chrome浏览器64位支持
-
【巴士速递·移动情报站】上周,谷歌为Windows7和8系统用户推出了64位版本的Chrome浏览器Beta测试版。现在,谷歌悄悄的为Canary和Dev分支Mac版Chrome浏览器增加了64位支...
- 谷歌发布64位Chrome for Mac 首个测试版
-
投稿by:水木之向来源:威锋网PostTime:2014-08-2921:52:52以下为文章全文:威锋网8月29日消息,在发布64位ChromeforWindows之后,谷歌日...
- Google Stadia首发支持设备中确认有Pixel 4和Pixel 2系列
-
2019-10-3110:20谷歌今天宣布扩充GoogleStadia的首发支持设备规模,继Pixel3系列、Pixel3a系列之外还添加了Pixel4系列和Pixel2系列四款机型。据...
- 64位谷歌浏览器Chrome 11月登陆苹果OS X
-
IT之家(www.ithome.com):64位谷歌浏览器Chrome11月登陆苹果OSX谷歌将于11月正式发布非beta版的、苹果OSX系统的64位谷歌浏览器,谷歌于一个月前曾推出beta版的...
- 外媒:谷歌推出了搭载苹果M1芯片Mac的Chrome版本
-
据外媒TheVerge消息,谷歌日前为苹果的ArmMacs发布了Chrome的本地版本。不过该版本原本是在周二开始推出,但由于意外崩溃而暂停了。Chrome产品经理MarkChang表示,谷歌计...