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程序文件一个服务器,没办法指定其他服务器的地址,本人才疏学浅,哪位大哥 ...
随机推荐
- php Yii2图片的url自动加localhost
解决方法:在地址前加http://,这样url就是绝对地址,不加的话是相对地址,游览器会自动转换,即加localhost
- java 面试,java 后端面试,数据库方面对初级和高级程序员的要求
本内容摘自 java web轻量级开发面试教程 对于合格的程序员,需要有基本的数据库操作技能,具体体现在以下三个方面. l 第一,针对一类数据库(比如MySQL.Oracle.SQL Server等 ...
- Nodejs进阶:使用DiffieHellman密钥交换算法
## 简介 Diffie-Hellman(简称DH)是密钥交换算法之一,它的作用是保证通信双方在非安全的信道中安全地交换密钥.目前DH最重要的应用场景之一,就是在HTTPS的握手阶段,客户端.服务端利 ...
- 深入理解JVM(七)——性能监控工具
前言 工欲善其事必先利其器,性能优化和故障排查在我们大都数人眼里是件比较棘手的事情,一是需要具备一定的原理知识作为基础,二是需要掌握排查问题和解决问题的流程.方法.本文就将介绍利用性能监控工具,帮助开 ...
- Web开发中常用的状态码
在HtttpServletResponse类中有关于状态码的描述. static int SC_ACCEPTED Status code (202) indicating that a request ...
- OC
一,字符串 1创建一个字符串 1) NSString *str2=[[NSString alloc]initWithString:str1]; 2) NSString *string2=[[NSSt ...
- Python教程百度网盘哪里有?
Python为我们提供了非常完善的基础代码库,覆盖了网络.文件.GUI.数据库.文本等大量内容,被形象地称作"内置电池(batteries included)".带你快速入门的Py ...
- TC358749XBG:HDMI转MIPI CSI芯片简介
TC358749XBG是一颗HDMI转MIPI CSI功能的视频转换芯片,分辨率:1920*1080,电源3.3/1.8/1.2,通信方式:IIC,封装形式BGA80
- Cognos报表调度与作业管理
本文针对Cognos的报表调度和作业管理做案例分析.为了测试报表定时调度功能,本文将报表定时输出到指定的归档目录. 1. 测试环境 Cognos V11.0 2. 设置档案文件根目录 Cognos报 ...
- java设计模式系列之设计模式概要(1)
一.什么是设计模式 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代码可靠性. ...