JAVA实现上传文件到服务器、删除服务器文件
使用的jar包:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
文件上传也可以使用scp,但是最后实现发现scp特别困难,而且只能实现上传这一个功能。如果要实现文件的删除则需要使用其他命令。
而sftp则是建立一个ssh通道,然后可以很方便的在通道内执行一系列命令,如put, get, rm, mkdir, rmdir,从而可以方便的管理远程服务器的文件。
下面介绍下Java实现。
首先我们创建一个pojo,将所有的账号信息及远程服务器信息都封装一下。
package com.snow.sftp; import lombok.Data; @Data
public class SftpAuthority {
private String host; // 服务器ip或者主机名
private int port; // sftp端口
private String user; // sftp使用的用户
private String password; // 账户密码
private String privateKey; // 私钥文件名
private String passphrase; // 私钥密钥 public SftpAuthority(String user, String host, int port) {
this.host = host;
this.port = port;
this.user = user;
}
}
在建立sftp通道过程中我们可以选择使用用户名密码的方式,也可以选择使用私钥(私钥可以有密钥)的方式。
建立一个service interface
package com.snow.sftp;
public interface SftpService {
void createChannel(SftpAuthority sftpAuthority);
void closeChannel();
boolean uploadFile(SftpAuthority sftpAuthority, String src, String dst);
boolean removeFile(SftpAuthority sftpAuthority, String dst);
}
具体实现:
package com.snow.sftp; 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.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import java.util.Properties; @Slf4j
@Service(value = "sftpService")
public class SftpServiceImpl implements SftpService { private Session session;
private Channel channel;
private ChannelSftp channelSftp; @Override
public void createChannel(SftpAuthority sftpAuthority) {
try {
JSch jSch = new JSch();
session = jSch.getSession(sftpAuthority.getUser(), sftpAuthority.getHost(), sftpAuthority.getPort()); if (sftpAuthority.getPassword() != null) {
// 使用用户名密码创建SSH
session.setPassword(sftpAuthority.getPassword());
} else if (sftpAuthority.getPrivateKey() != null) {
// 使用公私钥创建SSH
jSch.addIdentity(sftpAuthority.getPrivateKey(), sftpAuthority.getPassphrase());
} Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no"); // 主动接收ECDSA key fingerprint,不进行HostKeyChecking
session.setConfig(properties);
session.setTimeout(0); // 设置超时时间为无穷大
session.connect(); // 通过session建立连接 channel = session.openChannel("sftp"); // 打开SFTP通道
channel.connect();
channelSftp = (ChannelSftp) channel;
} catch (JSchException e) {
log.error("create sftp channel failed!", e);
}
} @Override
public void closeChannel() {
if (channel != null) {
channel.disconnect();
} if (session != null) {
session.disconnect();
}
} @Override
public boolean uploadFile(SftpAuthority sftpAuthority, String src, String dst) {
if (channelSftp == null) {
log.warn("need create channelSftp before upload file");
return false;
} if (channelSftp.isClosed()) {
createChannel(sftpAuthority); // 如果被关闭则应重新创建
} try {
channelSftp.put(src, dst, ChannelSftp.OVERWRITE);
log.info("sftp upload file success! src: {}, dst: {}", src, dst);
return true;
} catch (SftpException e) {
log.error("sftp upload file failed! src: {}, dst: {}", src, dst, e);
return false;
}
} @Override
public boolean removeFile(SftpAuthority sftpAuthority, String dst) {
if (channelSftp == null) {
log.warn("need create channelSftp before remove file");
return false;
} if (channelSftp.isClosed()) {
createChannel(sftpAuthority); // 如果被关闭则应重新创建
} try {
channelSftp.rm(dst);
log.info("sftp remove file success! dst: {}", dst);
return true;
} catch (SftpException e) {
log.error("sftp remove file failed! dst: {}", dst, e);
return false;
}
} }
调用示例:
package com.snow.sftp; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSftp { public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"sftp-application-context.xml"}); // 用户名密码方式
SftpService sftpService = context.getBean(SftpService.class);
SftpAuthority sftpAuthority = new SftpAuthority("user", "ip or host", port);
sftpAuthority.setPassword("user password"); sftpService.createChannel(sftpAuthority);
sftpService.uploadFile(sftpAuthority, "/home/snow/test/test.png", "/user/testaaa.png");
sftpService.removeFile(sftpAuthority, "/user/testaaa.png");
sftpService.closeChannel(); // 公私钥方式
sftpAuthority = new SftpAuthority("user", "ip or host", port);
sftpAuthority.setPrivateKey("your private key full path");
sftpAuthority.setPassphrase("private key passphrase");
sftpService.createChannel(sftpAuthority);
sftpService.uploadFile(sftpAuthority, "/home/snow/test/test.png", "/user/testaaa.png");
sftpService.removeFile(sftpAuthority, "/user/testaaa.png");
sftpService.closeChannel();
} }
除了本文介绍的put和rm操作以外,channelSftp还有很多其它的操作,比如get, mkdir, lcd, rename, rmdir, ls, lstat等,大家可以自行探索。
JAVA实现上传文件到服务器、删除服务器文件的更多相关文章
- java上传、下载、删除ftp文件
一共三个类,一个工具类Ftputil.,一个实体类Kmconfig.一个测试类Test 下载地址:http://download.csdn.net/detail/myfmyfmyfmyf/669710 ...
- java使用Jsch实现远程操作linux服务器进行文件上传、下载,删除和显示目录信息
1.java使用Jsch实现远程操作linux服务器进行文件上传.下载,删除和显示目录信息. 参考链接:https://www.cnblogs.com/longyg/archive/2012/06/2 ...
- [CentOs7]搭建ftp服务器(3)——上传,下载,删除,重命名,新建文件夹
摘要 上篇文章介绍了如何为ftp添加虚拟用户,本篇将继续实践如何上传,下载文件. 上传 使用xftp客户端上传文件,如图所示 此时上传状态报错,查看详情 从错误看出是应为无法创建文件造成的.那么我们就 ...
- Java下载https文件上传到阿里云oss服务器
Java下载https文件上传到阿里云oss服务器 今天做了一个从Https链接中下载音频并且上传到OSS服务器,记录一下希望大家也少走弯路. 一共两个类: 1 .实现自己的证书信任管理器类 /** ...
- MVC图片上传、浏览、删除 ASP.NET MVC之文件上传【一】(八) ASP.NET MVC 图片上传到服务器
MVC图片上传.浏览.删除 1.存储配置信息 在web.config中,添加配置信息节点 <appSettings> <add key="UploadPath" ...
- java实现上传文件夹
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 首先我们需要了解的是上传文件三要素: 1.表单提交方式:post (get方式提交有大小 ...
- java servlet上传centos服务器
前面一篇随笔说了Centos上架设javaWeb运行环境的方法,这篇主要讲打包上传服务器. 一.数据库连接文件.propeties 为了数据库安全,mysql3306端口访问我做了ip访问限制,由于m ...
- C#通过FTP账号上传、修改、删除文件 FTPClient
下面类文件中,主要做的工作是:从ftp服务器上下载文件把本地文件替换.添加.或删除功能,在替换本地文件时会先备份一下本地的文件,若整个操作都完成了就会发出commit命令,表示全部替换成功.若中间操作 ...
- Java ftp上传文件方法效率对比
Java ftp上传文件方法效率对比 一.功能简介: txt文件采用ftp方式从windows传输到Linux系统: 二.ftp实现方法 (1)方法一:采用二进制流传输,设置缓冲区,速度快,50M的t ...
- PHP文件上传至另一台服务器
PHP程序上传文件时,想指定上传到另一台服务器. move_uploaded_file这个方法第二个参数指定的存放路径需要和php程序文件一个服务器,没办法指定其他服务器的地址,本人才疏学浅,哪位大哥 ...
随机推荐
- Python数据类型-布尔/数字/字符串/列表/元组/字典/集合
代码 bol = True # 布尔 num = 100000000; # 数字 str = "fangbei"; # 字符串 str_cn = u"你好,方倍" ...
- Android笔记: fragment简单例子
MainActivity.java public class MainActivity extends Activity { @Override protected void onCreate(Bun ...
- 在Linux环境下搭建Tomcat+mysql+jdk环境
按照下面的步骤一步一步来搭建tomcat+jdk+mysql环境. [Linux环境]------我搭建的是64位centos版本的linux系统 1.下载并安装一个VMware workstat ...
- 小爬新浪新闻AFCCL
1.任务目标: 爬取新浪新闻AFCCL的文章:文章标题.时间.来源.内容.评论数等信息. 2.目标网页: http://sports.sina.com.cn/z/AFCCL/ 3.网页分析 4.源代码 ...
- Why I donot give up cnblogs for Jianshu
我为什么不放弃博客园使用简书 Why I donot give up cnblogs for Jianshu Chapter0 从2016年8月开始接触简书开始,就有些喜欢上简书了,因为简书支持 ma ...
- Python 的经典入门书籍有哪些?
是不是很多人跟你说,学Python开发就该老老实实地找书来看,再配合死命敲代码?电脑有了,软件也有了,心也收回来了?万事俱备,唯独只欠书籍?没找到到合适的书籍?可以看看这些. 1.Python基础教程 ...
- MongoDB对应SQL语句
-------------------MongoDB对应SQL语句------------------- 1.Create and Alter 1. sql: crea ...
- 三,ESP8266 SPI
重点是说SPI通信协议,,,, 不要害怕协议因为协议是人规定的,,刚好我也是人......规定的协议既然能成为规范让所有人所接受,那么必然有它的优势和优点,必然值得学习,, 害怕协议的人是因为当初碰到 ...
- MongoDB学习之路(五)
MongoDB $type 操作符 类型 数字 备注 Double 1 String 2 Object 3 Array 4 Binary data 5 Undefined 6 已废弃 Object i ...
- 团队作业8——第二次项目冲刺(Beta阶段)5.21
1.当天站立式会议照片 会议内容: 本次会议为第三次会议 本次会议在陆大楼2楼召开,本次会议内容: ①:检查总结第二次任务完成情况 ②:布置第三次任务的详细分工 ③:规定完成时间是在第四次任务之前 ④ ...