当前位置: 首页 > news >正文

SpringBoot连接Sftp服务器实现文件上传/下载(亲测可用)

目录

一、先导入pom依赖

二、工具类完整代码 


一、先导入pom依赖

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

二、工具类完整代码 

package com.example.excel.util;import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import java.util.Vector;/*** SFTP工具类* 功能:测试连接、下载文件、上传文件*/
public class SftpUtil {private static final Logger log = LoggerFactory.getLogger(SftpUtil.class);private final String host;private final int port;private final String username;private final String password;private Session session;private ChannelSftp channel;public SftpUtil(String host, int port, String username, String password) {this.host = host;this.port = port;this.username = username;this.password = password;}/*** 测试SFTP连接* @return true连接成功,false连接失败*/public boolean testConnection() {try {connect();return true;} catch (JSchException e) {log.error("SFTP连接测试失败: {}", e.getMessage());return false;} finally {disconnect();}}/*** 下载文件* @param remotePath 远程文件路径* @param localPath 本地保存路径* @return true下载成功,false下载失败*/public boolean downloadFile(String remotePath, String localPath) {try (OutputStream output = Files.newOutputStream(Paths.get(localPath))) {connect();channel.get(remotePath, output);log.info("文件下载成功: {} -> {}", remotePath, localPath);return true;} catch (JSchException | SftpException | IOException e) {log.error("文件下载失败: {}", e.getMessage());return false;} finally {disconnect();}}/*** 上传文件* @param localPath 本地文件路径* @param remotePath 远程保存路径* @return true上传成功,false上传失败*/public boolean uploadFile(String localPath, String remotePath) {try (InputStream input = Files.newInputStream(Paths.get(localPath))) {connect();// 1. 提取远程目录路径String remoteDir = extractDirectoryPath(remotePath);// 2. 确保目录存在(不存在则创建)ensureDirectoryExists(remoteDir);channel.put(input, remotePath);log.info("文件上传成功: {} -> {}", localPath, remotePath);return true;} catch (JSchException | SftpException | IOException e) {log.error("文件上传失败: {}", e.getMessage());return false;} finally {disconnect();}}/*** 检查远程文件是否存在* @param remotePath 远程文件路径* @return true存在,false不存在*/public boolean fileExists(String remotePath) {try {connect();channel.lstat(remotePath);return true;} catch (SftpException e) {if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {return false;}log.error("检查文件存在时出错: {}", e.getMessage());return false;} catch (JSchException e) {log.error("连接异常: {}", e.getMessage());return false;} finally {disconnect();}}/*** 创建SFTP连接*/private void connect() throws JSchException {if (channel != null && channel.isConnected()) {return;}JSch jsch = new JSch();session = jsch.getSession(username, host, port);session.setPassword(password);// 配置不检查主机密钥(生产环境应配置known_hosts)Properties config = new Properties();config.put("StrictHostKeyChecking", "no");session.setConfig(config);session.connect();Channel channel = session.openChannel("sftp");channel.connect();this.channel = (ChannelSftp) channel;}/*** 从文件路径中提取目录路径* @param filePath 完整文件路径* @return 目录路径*/private String extractDirectoryPath(String filePath) {int lastSlash = filePath.lastIndexOf('/');if (lastSlash <= 0) {return "/"; // 根目录}return filePath.substring(0, lastSlash);}/*** 确保远程目录存在(不存在则递归创建)* @param remoteDir 远程目录路径*/private void ensureDirectoryExists(String remoteDir) throws SftpException {try {// 尝试进入目录(存在则直接返回)channel.cd(remoteDir);} catch (SftpException e) {// 目录不存在,需要创建if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {// 递归创建父目录int lastSlash = remoteDir.lastIndexOf('/');if (lastSlash > 0) {String parentDir = remoteDir.substring(0, lastSlash);ensureDirectoryExists(parentDir);}// 创建当前目录channel.mkdir(remoteDir);channel.cd(remoteDir); // 进入新创建的目录log.debug("创建目录: {}", remoteDir);} else {throw e; // 其他异常重新抛出}}}/*** 断开SFTP连接*/private void disconnect() {if (channel != null) {channel.disconnect();channel = null;}if (session != null) {session.disconnect();session = null;}}// 使用示例public static void main(String[] args) {// 1. 创建SFTP工具实例SftpUtil sftp = new SftpUtil("10.10.10.10",2222,"username","password");// 2. 测试连接System.out.println("连接测试: " + (sftp.testConnection() ? "成功" : "失败"));// 3. 检查文件是否存在String remoteFile = "/remote/path/test.txt";System.out.println("文件存在检查: " + (sftp.fileExists(remoteFile) ? "存在" : "不存在"));// 4. 下载文件sftp.downloadFile("/upload/test/test.zip", "D:\\local.zip");// 5. 上传文件sftp.uploadFile("C:\\Users\\test\\Desktop\\log.log", "/upload/test/test.log");}
}

http://www.dtcms.com/a/299081.html

相关文章:

  • Java中List集合对象去重及按属性去重
  • 【Linux系统】理解硬件 | 引入文件系统
  • MySQL数据库本地迁移到云端完整教程
  • 部署上线你的项目
  • 【Git】实用Git操作指南:从入门到高效协作
  • 小米携手云轴科技ZStack获信通院可信云用户典型实践奖
  • 大语言模型 LLM 通过 Excel 知识库 增强日志分析,根因分析能力的技术方案(2):LangChain + LlamaIndex 实现
  • Nanopct6SDK问题汇总与解决方案
  • 【架构】Docker简单认知构建
  • 【工程化】浅谈前端构建工具
  • Python爬虫实战:研究purl库相关技术
  • Mistral AI开源 Magistral-Small-2507
  • 密码学系列 - 密钥派生
  • 界面规范3-列表下
  • “给予” 超越 “莲花”,支持图片在线编辑
  • AI是否会终结IT职业?深度剖析IT行业的“涌现”与重构
  • 【GaussDB】构建一个GaussDB的Docker镜像
  • 【GaussDB】如何从GaussDB发布包中提取出内核二进制文件
  • window下MySQL安装(二)疑难解答
  • Apache Doris Data Agent 解决方案:开启智能运维与数据治理新纪元
  • excel删除重复项场景
  • Java面试题及详细答案120道之(021-040)
  • 字节跳动扣子 Coze 宣布开源:采用 Apache 2.0 许可证,支持商用
  • Qt 远程过程调用(RPC)实现方案
  • 网络基础19--OSPF路由业务多区域
  • 【Android】相对布局应用-登录界面
  • Java 中 System 类零度解析
  • 4N90-ASEMI电机控制专用4N90
  • 【数据结构】树的概念
  • 统计与大数据分析与数学金融课程解析