springBoot整合sftp

1.引入依赖,pom文件添加依赖。

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

2.在application.yml文件添加sftp配置。

sftp:protocol: sftp #协议host: 127.0.0.1 # ipport: 22 # 端口username: alexpassword: ******

3.编写SftpProperties。

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Data
@Component
@ConfigurationProperties(prefix = "sftp")
public class SftpProperties {private String protocol;private String host;private Integer port;private String username;private String password;
}

4.编写SftpUtils。

import com.jcraft.jsch.*;
import com.yeyoo.sftp.config.SftpProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Slf4j
@Service
public class SftpUtils {@Autowiredprivate SftpProperties config;/*** 创建SFTP连接* @return* @throws Exception*/public ChannelSftp createSftp() throws Exception {JSch jsch = new JSch();log.info("Try to connect sftp[" + config.getUsername() + "@" + config.getHost() + "], use password[" + config.getPassword() + "]");Session session = createSession(jsch, config.getHost(), config.getUsername(), config.getPort());session.setPassword(config.getPassword());session.setConfig("StrictHostKeyChecking", "no");session.connect();log.info("Session connected to {}.", config.getHost());Channel channel = session.openChannel(config.getProtocol());channel.connect();log.info("Channel created to {}.", config.getHost());return (ChannelSftp) channel;}/*** 创建session* @param jsch* @param host* @param username* @param port* @return* @throws Exception*/public Session createSession(JSch jsch, String host, String username, Integer port) throws Exception {Session session = null;if (port <= 0) {session = jsch.getSession(username, host);} else {session = jsch.getSession(username, host, port);}if (session == null) {throw new Exception(host + " session is null");}return session;}/*** 关闭连接* @param sftp*/public void disconnect(ChannelSftp sftp) {try {if (sftp != null) {if (sftp.isConnected()) {sftp.disconnect();} else if (sftp.isClosed()) {log.info("sftp is closed already");}if (null != sftp.getSession()) {sftp.getSession().disconnect();}}} catch (JSchException e) {e.printStackTrace();}}}

5.编写SftpFileService。

public interface SftpFileService {boolean uploadFile(String sftpPath,String targetPath,String sftpFileName,String targetFileName) throws Exception;boolean downloadFile(String sftpPath,String targetPath,String sftpFileName,String targetFileName) throws Exception;}

6.编写SftpFileServiceImpl。

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import com.yeyoo.sftp.service.SftpFileService;
import com.yeyoo.sftp.utils.SftpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Vector;/*** @description: SFTP文件服务实现类* @author: wzg* @create: 2021-09-17**/@Slf4j
@Service
public class SftpFileServiceImpl implements SftpFileService {@Autowiredprivate SftpUtils sftpUtils;/**** @param sftpPath  sftp文件目录* @param targetPath  目标存放文件目录* @param sftpFileName  sftp文件名* @param targetFileName  下载保存文件名* @return* @throws Exception*/@Overridepublic boolean downloadFile(String sftpPath, String targetPath,String sftpFileName,String targetFileName) throws Exception {long start = System.currentTimeMillis();// 开启sftp连接ChannelSftp sftp = sftpUtils.createSftp();OutputStream outputStream = null;try {boolean isExist = isDirExist(sftpPath,sftp);// sftp文件夹存在if(isExist){// 进入sftp文件目录sftp.cd(sftpPath);log.info("Change path to {}", sftpPath);File file = new File(targetPath+targetFileName);// 如果文件已经存在,删除if (file.exists()) {file.delete();}// 创建文件夹new File(targetPath).mkdirs();// 创建文件file.createNewFile();outputStream = new FileOutputStream(file);if(sftpFileName.equals("")){Vector fileList = sftp.ls(sftpPath);Iterator it = fileList.iterator();while (it.hasNext()) {ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();sftpFileName = entry.getFilename();}}// 下载文件sftp.get(sftpFileName, outputStream);log.info("{} Download file success. TargetPath: {},Total time {}ms.",targetFileName, targetPath,System.currentTimeMillis()-start);return true;}else{log.info("sftp文件夹不存在");return false;}} catch (Exception e) {log.error("Download file failure. targetFileName: {}", targetFileName, e);throw new Exception(targetFileName+" Download File failure");} finally {if (outputStream != null) {outputStream.close();}// 关闭sftpsftpUtils.disconnect(sftp);}}/**** @param sftpPath  sftp文件目录* @param localPath  本地存放文件目录* @param sftpFileName  sftp文件名* @param localFileName  本地文件名* @return* @throws Exception*/@Overridepublic boolean uploadFile(String sftpPath, String localPath, String sftpFileName, String localFileName) throws Exception {// 开启sftp连接ChannelSftp sftp = sftpUtils.createSftp();FileInputStream in = null;try {// 进入sftp文件目录sftp.cd(sftpPath);log.info("Change path to {}", sftpPath);File localFile = new File(localPath+localFileName);in = new FileInputStream(localFile);// 上传文件sftp.put(in, sftpFileName);log.info("upload file success. TargetPath: {}", sftpPath);return true;} catch (Exception e) {log.error("upload file failure. sftpPath: {}", sftpPath, e);throw new Exception("upload File failure");} finally {if (in != null) {in.close();}// 关闭sftpsftpUtils.disconnect(sftp);}}/*** 判断目录是否存在* @param directory* @return*/public boolean isDirExist(String directory,ChannelSftp sftp){boolean isDirExistFlag = false;try{SftpATTRS sftpATTRS = sftp.lstat(directory);isDirExistFlag = true;return sftpATTRS.isDir();}catch (Exception e){if (e.getMessage().toLowerCase().equals("no such file")){isDirExistFlag = false;}}return isDirExistFlag;}}

7.编写SftpFileController进行测试。

import com.yeyoo.sftp.service.SftpFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.File;
import java.util.HashMap;
import java.util.Map;@RestController
@RequestMapping("/sftp")
public class SftpFileController {@Autowiredprivate SftpFileService sftpFileService;@RequestMapping("/downLoad")public Map downLoad() throws Exception {String sftpPath = "/update_data/20210909/";String sftpFileName = "test.csv.gz";String targetPath = "/data/tianyancha/";String targetFileName = "company_wechat.csv.gz";File file = sftpFileService.downloadFile(sftpPath,targetPath,sftpFileName,targetFileName);Map map = new HashMap<>();map.put("code",200);map.put("message","success");map.put("data",file);return map;}
}

springBoot整合sftp相关推荐

  1. Springboot整合sftp、scp

    Springboot整合sftp 一.网址 官网:http://www.jcraft.com/jsch/ 博客:https://blog.csdn.net/qq_39361915/article/de ...

  2. SpringBoot整合Guacamole

    前言 本文主要介绍的是SpringBoot如何整合Guacamole在浏览器是远程桌面的访问. Guacamole 介绍 Apache Guacamole 是一个无客户端远程桌面网关.它支持标准协议, ...

  3. SpringBoot第九篇: springboot整合Redis

    这篇文章主要介绍springboot整合redis,至于没有接触过redis的同学可以看下这篇文章:5分钟带你入门Redis. 引入依赖: 在pom文件中添加redis依赖: <dependen ...

  4. es springboot 不设置id_原创 | 一篇解决Springboot 整合 Elasticsearch

    ElasticSearch 结合业务的场景,在目前的商品体系需要构建搜索服务,主要是为了提供用户更丰富的检索场景以及高速,实时及性能稳定的搜索服务. ElasticSearch是一个基于Lucene的 ...

  5. springboot整合shiro使用shiro-spring-boot-web-starter

    此文章仅仅说明在springboot整合shiro时的一些坑,并不是教程 增加依赖 <!-- 集成shiro依赖 --> <dependency><groupId> ...

  6. db2 springboot 整合_springboot的yml配置文件通过db2的方式整合mysql的教程

    springboot整合MySQL很简单,多数据源就master,slave就行了,但是在整合DB2就需要另起一行,以下是同一个yml文件 先配置MySQL,代码如下 spring: datasour ...

  7. 九、springboot整合rabbitMQ

    springboot整合rabbitMQ 简介 rabbitMQ是部署最广泛的开源消息代理. rabbitMQ轻量级,易于在内部和云中部署. 它支持多种消息传递协议. RabbitMQ可以部署在分布式 ...

  8. 八、springboot整合Spring Security

    springboot整合Spring Security 简介 Spring Security是一个功能强大且可高度自定义的身份验证和访问控制框架.它是保护基于Spring的应用程序的事实标准. Spr ...

  9. 六、springboot整合swagger

    六.springboot整合swagger 简介 swagger 提供最强大,最易用的工具,以充分利用OpenAPI规范. 官网 : https://swagger.io/ 准备工作 pom.xml ...

最新文章

  1. 树链剖分(轻重链剖分) 讲解 (模板题目 P3384 【模板】轻重链剖分 )
  2. 操作系统:连续分配、分页和分段三种存储分配机制的优缺点
  3. C++ 成员函数做友元
  4. php mysql刷新表格_php读入mysql数据并以表格形式显示(表单实现无刷新提交)
  5. appium学习记录1
  6. Java面试——SpringMVC系列总结
  7. 监控mysql锁定状态_企业实战Mysql不停机维护主从同步
  8. HTTP 错误 403.14 - Forbidden Web 服务器被配置为不列出此目录的内容
  9. anaconda的python环境下无法使用通过pip安装的python库
  10. 20150823 命令练习总结
  11. 计算机电路基础 - 1,计算机电路基础1.1(4页)-原创力文档
  12. 最小二乘法求回归直线方程的推导过程
  13. 20年,中国互联网主流产品的演变和逻辑
  14. 【Unity】 HTFramework框架(十四)Audio音频管理器
  15. java 中奖_java的if判断是否中奖了(21)
  16. java文件上传像素限制,JS上传图片前的限制包括(jpg jpg gif及大小高宽)等
  17. 教你用Python如何完成一个查票系统实现123006自动抢票啦~
  18. win10下VMware15安装centos7详细步骤及遇到的问题
  19. 【英语-同义词汇词组】advantage | ascendancy | predominance | preponderance | prepotency | superh的用法及区别
  20. python人脸识别解锁电脑_Python 实现在 App 端的人脸识别!手机解锁人脸识别!

热门文章

  1. 李宏毅学习笔记11.CNN(上)
  2. 评测TFN F4 高性能OTDR光时域反射仪性能
  3. STM32F4+DP83848以太网通信指南系列知识储备
  4. python基础_字典_列表_元组考试
  5. 里氏代换原则C#详解
  6. vue列表的单独展开收起和全部展开收起
  7. 【经验科普】实战分析C工程代码可能遇到的编译问题及其解决思路
  8. 国际物流专线是什么意思?
  9. 苹果电脑可以装windows系统吗_iPhone 可以装 windows 了,想不想试试?
  10. 安全技术与相关安全工具