sftp作为临时的文件存储位置,在某些场合还是有其应景的,比如对账文件存放。需要提供一个上传的工具类。实现方法参考下:

pom.xml中引入类库:

        <dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

sftp工具类和使用命令行是一样的操作方法,上传下载如下:

public class SftpUploadTest {

    private ChannelSftp sftp = null;

    private Session sshSession = null;

    private String username;

    private String password;

    private String host;

    private int port;

    public SftpUploadTest(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
} /**
* 连接sftp服务器
*
* @return ChannelSftp sftp连接实例
*/
public ChannelSftp connect() {
info("-->sftp连接开始>>>>>> " + host + ":" + port + " >>>username=" + username);
JSch jsch = new JSch();
try {
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no");
sshSession.setConfig(properties);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
info(" ftp Connected to " + host + ":" + port);
} catch (JSchException e) {
throw new RuntimeException("sftp连接失败", e);
}
return sftp;
} /**
* 下载单个文件,如果指定文件名,则下载到文件名否则保持原有文件名
*
* @param remoteFilePath 远程文件路径 /tmp/xxx.txt || xxx.txt.zip
* @param localFilePath 本地文件路径 如 D:\\xxx.txt
* @return 下载的文件
*/
public File downloadFile(String remoteFilePath, String localFilePath) {
info(">>>>>>>>>downloadFile--ftp下载文件" + remoteFilePath + "开始>>>>>>>>>>>>>");
connect();
String remoteFileName = "";
// 远端目录确定以 / 作为目录格式
String rFileSeparator = "/";
int rDirNameSepIndex = remoteFilePath.lastIndexOf(rFileSeparator) + 1;
String rDir = remoteFilePath.substring(0, rDirNameSepIndex);
remoteFileName = remoteFilePath.substring(rDirNameSepIndex);
if(localFilePath.endsWith(File.separator)) {
localFilePath = localFilePath + (localFilePath.endsWith(File.separator) ? remoteFileName : "/" + remoteFileName);
}
File file = null;
OutputStream output = null;
try {
file = new File(localFilePath);
if (file.exists()) {
file.delete();
}
file.createNewFile();
sftp.cd(rDir);
output = new FileOutputStream(file);
sftp.get(remoteFileName, output);
info("===DownloadFile:" + remoteFileName + " success from sftp.");
} catch (SftpException e) {
error("ftp下载文件失败", e);
} catch (FileNotFoundException e) {
error("本地目录异常,请检查" + file.getPath(), e);
} catch (IOException e) {
error("创建本地文件失败" + file.getPath(), e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
disconnect();
} info(">>>>>>>>>downloadFile--ftp下载文件结束>>>>>>>>>>>>>");
return file;
} /**
* 上传单个文件,如果指正下载文件名则使用,否则保留原有文件名
*
* @param remoteFilePath 远程文件路径 /tmp/xxx.txt ||xxx.txt.zip
* @param uploadFilePath 要上传的文件 如:D:\\test\\xxx.txt
*/
public void uploadFile(String remoteFilePath, String uploadFilePath) {
info(" begin uploadFile from:" + uploadFilePath +
", to: " + remoteFilePath);
FileInputStream in = null;
connect();
String remoteFileName = "";
String remoteDir = remoteFilePath;
String localFileName = "";
// 远端目录确定以 / 作为目录格式
String rFileSeparator = "/";
if(remoteFilePath.endsWith(rFileSeparator)) {
localFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf(File.separator) + 1);
remoteFileName = localFileName;
} else {
int fileNameDirSep = remoteFilePath.lastIndexOf(rFileSeparator) + 1;
remoteDir = remoteFilePath.substring(0, fileNameDirSep);
remoteFileName = remoteFilePath.substring(fileNameDirSep);
}
try {
sftp.cd(remoteDir);
} catch (SftpException e) {
try {
sftp.mkdir(remoteDir);
sftp.cd(remoteDir);
} catch (SftpException e1) {
error("ftp创建文件路径失败,路径为" + remoteDir);
throw new RuntimeException("ftp创建文件路径失败" + remoteDir);
}
}
File file = new File(uploadFilePath);
try {
in = new FileInputStream(file);
sftp.put(in, remoteFileName);
} catch (FileNotFoundException e) {
error("文件不存在-->" + uploadFilePath);
} catch (SftpException e) {
error("sftp异常-->", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
info("Close stream error." + e.getMessage());
}
}
disconnect();
}
info(">>>>>>>>>uploadFile--ftp上传文件结束>>>>>>>>>>>>>");
} /**
* 关闭连接
*/
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
this.sftp = null;
info("sftp 连接已关闭!");
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
this.sshSession = null;
info("sshSession 连接已关闭!");
}
}
}
private void info(String msg) {
System.out.println("info: " + msg);
} private void error(String msg) {
error(msg, null);
} private void error(String msg, Throwable e) {
System.out.println("error: " + msg);
if(e != null) {
e.printStackTrace();
}
} public static void main(String[] args) throws Exception {
SftpUploadTest uploadTest = new SftpUploadTest("root", "123", "10.40.10.17", 52766);
uploadTest.uploadFile("/tmp/" + "readme-" + System.currentTimeMillis() + ".txt", "C:\\Users\\xx\\Desktop\\sample\\readme.txt");
uploadTest.downloadFile("/tmp/readme.txt", "C:\\Users\\xx\\Desktop\\sample\\readme-" + System.currentTimeMillis() + ".txt");
}
}

  使用时,可根据需要进行连接的适时释放!也可能为了安全需要,添加一些额外的安全指令!

  sftp文件操作的命令罗列如下参考:

sftp常用的为上传下载

# get
# 从远程服务器上下载一个文件存放到本地,如下:
# 先通过lcd切换到本地那个目录下,然后通过get file
>> lcd d:\ #表示切换到本地的d盘下
>> get ./test.sql   #这样就将当前文件下载本地的d盘下
# put
# 是将本地的文件上传到远程服务器上,如下:
>> put #在windows下弹出选择文件的窗口
# lcd
# 先通过lcd切换到本地那个目录下
>> lcd c:\ #表示切换到本地的c盘下
# lls
#显示当前目录下的所有文件
>> pwd #显示当前目录

java实操之使用jcraft进行sftp上传下载文件的更多相关文章

  1. SFTP上传下载文件、文件夹常用操作

    SFTP上传下载文件.文件夹常用操作 1.查看上传下载目录lpwd 2.改变上传和下载的目录(例如D盘):lcd  d:/ 3.查看当前路径pwd 4.下载文件(例如我要将服务器上tomcat的日志文 ...

  2. Java Sftp上传下载文件

    需要使用jar包  jsch-0.1.50.jar sftp上传下载实现类 package com.bstek.transit.sftp; import java.io.File; import ja ...

  3. curl实现SFTP上传下载文件

    摘自:https://blog.csdn.net/swj9099/article/details/85292444 #include <stdio.h> #include <stdl ...

  4. THINKPHP 3.2 PHP SFTP上传下载 代码实现方法

     一.SFTP介绍:使用SSH协议进行FTP传输的协议叫SFTP(安全文件传输)Sftp和Ftp都是文件传输协议.区别:sftp是ssh内含的协议(ssh是加密的telnet协议),  只要sshd服 ...

  5. java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)

    1.汉语转拼音: import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuP ...

  6. Xshell5下利用sftp上传下载传输文件

    sftp是Secure File Transfer Protocol的缩写,安全文件传送协议.可以为传输文件提供一种安全的加密方法.sftp 与 ftp 有着几乎一样的语法和功能.SFTP 为 SSH ...

  7. SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例

    本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...

  8. java web service 上传下载文件

    1.新建动态web工程youmeFileServer,新建包com,里面新建类FileProgress package com; import java.io.FileInputStream; imp ...

  9. 【转】Java IOUtils方式上传下载文件 on HDFS

    [From]https://www.cnblogs.com/areyouready/p/9795442.html package com.css.hdfs04; import java.io.File ...

随机推荐

  1. selenium+java定位163/126邮箱元素显示定位失败解决

    开始在没有进入iframe时,用任何方法定位163/126邮箱登录页面的元素都不可能定位到,eclipse工作台会显示Unable to locate element:…… 这种情况我遇到了两种原因: ...

  2. BaseDao.util(虎大将军)

    package logistics.util; import java.sql.Connection; import java.sql.PreparedStatement; import java.s ...

  3. AHOI——Day1个人感悟

    今天,是个bilibili的日子.(嗯?什么意思?) 洛谷已经尽力了: 于是我带着洛谷的祝福,来到了AHOI的考场--合肥一中. 其实我是考完才签到的,我一大早五点多就起来了,到考场后,在肯德基吃了早 ...

  4. 解决使用Mybatis 传入多参数使用map封装遇到的 “坑”问题

    好久没来写些东西了,今天 我分享一下自己遇到的一个“小 坑”,这也许对您来说不是个问题,但是我还是希望对没有遇到过这类问题的朋友给个小小的帮助吧 是这样的,需求:需要实现根据多条件 且分页展示数据 1 ...

  5. 别人的Linux私房菜(15)磁盘配额与高级文件系统管理

    磁盘配额在网站.邮件.文件等服务器常见,主要有针对用户.用户组.限制某一目录的的最大磁盘配额. ext文件系统进能针对整个文件系统配额,xfs可以针对目录配额.配额和文件系统有关. 内核必须支持磁盘配 ...

  6. 第八周助教工作总结——NWNU李泓毅

    1.助教博客链接: https://www.cnblogs.com/NWNU-LHY/ 2.作业要求博客链接: http://www.cnblogs.com/nwnu-daizh/p/10687492 ...

  7. Js高级程序设计~读书笔记

    1.函数-函数声明和函数表达式 解析器在向执行环境加载数据时,函数声明和函数表达式的对待不同. 解析器会率先执行函数声明,将会在任何使用到它的地方前加载, 而对于函数表达式,只会在执行到的时候去加载: ...

  8. Python的基本类型介绍和可变不可变

    Python的基本类型介绍 前言 做python有一段时间了,从工作开始就在不断地学习和积累.但是有时候用到一些技术点,甚至是基础知识的时候,总是会遗忘.所以,从今天开始,就在这里记录下来,不仅可以分 ...

  9. 贝叶斯公式52张牌猜黑桃A策略

    贝叶斯公式52张牌猜黑桃A策略 考虑有208平行世界,其中有4个世界(1/52)的黑桃A方在第一张牌的位置,余下204个世界中,有4个世界的黑桃A在第2张牌的位置,4个世界在第3张牌的位置..... ...

  10. linux (ubuntu) 命令学习笔记

    1, md5sum 输出字符串的MD5值 echo -n 123456 | md5sum //-n表示不打印回车符 2, ubuntu设置dock任务栏鼠标点击效果 16.04: 调整位置:gsett ...