SFTP工具类实现文件上传下载_

import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;/*** SFTP工具类*/
public class SftpFile {static Session sshSession = null;/*** 获取ChannelSftp*/public static ChannelSftp getConnectIP(String host, String sOnlineSftpPort, String username, String password) {int port = 0;if (!("".equals(sOnlineSftpPort)) && null != sOnlineSftpPort) {port = Integer.parseInt(sOnlineSftpPort);}ChannelSftp sftp = null;try {JSch jsch = new JSch();jsch.getSession(username, host, port);sshSession = jsch.getSession(username, host, port);sshSession.setPassword(password);Properties sshConfig = new Properties();sshConfig.put("StrictHostKeyChecking", "no");sshSession.setConfig(sshConfig);sshSession.connect();Channel channel = sshSession.openChannel("sftp");channel.connect();sftp = (ChannelSftp) channel;} catch (Exception e) {e.printStackTrace();}return sftp;}/*** 上传*/public static void upload(String directory, String uploadFile, ChannelSftp sftp) {FileInputStream io = null;try {sftp.cd(directory);File file = new File(uploadFile);io = new FileInputStream(file);sftp.put(io, file.getName());} catch (Exception e) {e.printStackTrace();} finally {if (null != io) {try {io.close();} catch (IOException e) {e.printStackTrace();}}if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}}//删除指定目录下的所有文件static boolean deleteDirFiles(String newsFile, ChannelSftp sftp) {try {sftp.cd(newsFile);ListIterator a = sftp.ls(newsFile).listIterator();while (a.hasNext()) {LsEntry oj = (LsEntry) a.next();SftpFile.delete(newsFile, oj.getFilename(), sftp);}} catch (Exception e) {e.getMessage();} finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}return true;}/*** 上传本地文件到sftp指定的服务器,** @param directory      目标文件夹* @param uploadFile     本地文件夹* @param sftp           sftp地址* @param remoteFileName 重命名的文件名字* @param isRemote       是否需要重命名  是true 就引用remoteFileName 是false就用默认的文件名字*/public static void upload(String directory, String uploadFile, ChannelSftp sftp, String remoteFileName, boolean isRemote) {FileInputStream io = null;try {boolean isExist = false;try {SftpATTRS sftpATTRS = sftp.lstat(directory);isExist = true;isExist = sftpATTRS.isDir();} catch (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isExist = false;}}if (!isExist) {boolean existDir = SftpFile.isExistDir(directory, sftp);if (!existDir) {String pathArry[] = directory.split("/");StringBuffer Path = new StringBuffer("/");for (String path : pathArry) {if (path.equals("")) {continue;}Path.append(path + "/");if (!SftpFile.isExistDir(Path + "", sftp)) {// 建立目录sftp.mkdir(Path.toString());// 进入并设置为当前目录}sftp.cd(Path.toString());}}}sftp.cd(directory);File file = new File(uploadFile);io = new FileInputStream(file);if (isRemote) {sftp.put(io, remoteFileName);} else {sftp.put(io, file.getName());}} catch (Exception e) {e.printStackTrace();} finally {if (null != io) {try {io.close();} catch (IOException e) {e.printStackTrace();}}if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}}public static boolean isExistDir(String path, ChannelSftp sftp) {boolean isExist = false;try {SftpATTRS sftpATTRS = sftp.lstat(path);isExist = true;return sftpATTRS.isDir();} catch (Exception e) {if (e.getMessage().toLowerCase().equals("no such file")) {isExist = false;}}return isExist;}/*** 上传目录下的多个文件*/public static List<String> uploadZip(String directory, String uploadFile, ChannelSftp sftp, List<String> filePath) {try {List<String> list = new ArrayList<>();boolean existDir = SftpFile.isExistDir(directory, sftp);if (!existDir) {sftp.mkdir(directory);}sftp.cd(directory);int i = 1;for (String newPath : filePath) {FileInputStream io = null;try {File file = new File(uploadFile + newPath);io = new FileInputStream(file);sftp.put(io, newPath);io.close();list.add(newPath);i++;} catch (Exception ex) {ex.printStackTrace();} finally {if (null != io) {try {io.close();} catch (IOException e) {e.printStackTrace();}}}}return list;} catch (SftpException e) {e.getMessage();return null;} finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}}/*** 下载指定文件*/public static void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {try {sftp.cd(directory);File file = new File(saveFile);sftp.get(downloadFile, new FileOutputStream(file));} catch (Exception e) {e.printStackTrace();} finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}System.out.println("DOWNLOAD SUCCESS!");}/*** 查看指定目录下的所有文件*/public static List<String> check(String directory, ChannelSftp sftp) {List<String> fileList = new ArrayList<>();try {sftp.cd(directory);ListIterator a = sftp.ls(directory).listIterator();while (a.hasNext()) {LsEntry oj = (LsEntry) a.next();System.out.println(oj.getFilename());//fileList.add((String) a.next());}} catch (Exception e) {e.printStackTrace();} finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}return fileList;}/*** 删除指定路径下的指定文件*/public static void delete(String directory, String deleteFile, ChannelSftp sftp) {try {sftp.cd(directory);sftp.rm(deleteFile);System.out.println("文件:"+deleteFile+" 删除成功!");} catch (Exception e) {e.printStackTrace();}finally {if (sftp.isConnected()) {sshSession.disconnect();sftp.disconnect();}}}public static void main(String[] args) {//服务器地址,端口,用户名,密码ChannelSftp ftp = getConnectIP("10.0.0.131", "22", "root", "123456");//上传单个文件
//        upload("/mydata/", "C:\\Users\\Administrator\\Desktop\\1.txt", ftp);
//        upload("/mydata/", "C:\\Users\\Administrator\\Desktop\\picture.zip", ftp);//上传文件并重命名
//        upload("/mydata/", "C:\\Users\\Administrator\\Desktop\\1.txt", ftp,"2.txt",true);//删除指定文件
//        delete("/mydata","1.txt",ftp);//查看指定目录下的所有文件
//        check("/mydata",ftp);//从服务器下载文件
//        download("/mydata","2.txt","C:\\Users\\Administrator\\Desktop\\2.txt",ftp);//同时上传多个文件
//        uploadZip("/mydata/picture", "C:\\Users\\Administrator\\Desktop\\picture\\", ftp, Arrays.asList("1.png","2.png"));//删除指定目录下的所有文件deleteDirFiles("/mydata/picture",ftp);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/pingmian/82592.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

RuoYi前后端分离框架将前端dist资源集成到Jar包中独立部署

一、背景 .NET体系下通常采用服务端渲染(如Razor Pages)或直接包含前端资源,而Java Spring Boot项目虽支持静态资源打包,但Vue CLI工程需要独立的构建流程。主管要求将编译后的Vue工程直接嵌入JAR包中方便维护,本人不推荐这样,原因有三: 第一、Vue CLI需要npm run buil…

基于 Flink+Paimon+Hologres 搭建淘天集团湖仓一体数据链路

摘要&#xff1a;本文整理自淘天集团高级数据开发工程师朱奥老师在 Flink Forward Asia 2024 流式湖仓论坛的分享。内容主要为以下五部分&#xff1a; 1、项目背景 2、核心策略 3、解决方案 4、项目价值 5、未来计划 01、项目背景 1.1 当前实时数仓架构 当前的淘天实时架构是从…

SIGCHLD信号--补充

进程一章讲过用wait和waitpid函数清理僵尸进程,父进程可以阻塞等待子进程结束,也可以非阻 塞地查询是否有子进程结束等待清理(也就是轮询的方式)。采用第一种方式,父进程阻塞了就不 能处理自己的工作了;采用第二种方式,父进程在处理自己的工作的同时还要记得时不时地轮询一 下,…

即插即用!全新记忆回溯策略:一种元启发式算法的进化更新机制,含完整免费MATLAB代码

1. 简介 元启发式算法的搜索域总是不断变化&#xff0c;这使得难以适应多样化的优化问题。为了克服上述问题&#xff0c;提出了一种称为记忆回溯策略&#xff08;MBS&#xff09;的进化更新机制&#xff0c;包括思维阶段、回忆阶段和记忆阶段。总体而言&#xff0c;MBS的采用通…

Spring AI框架快速入门

​​前言&#xff1a;在经历了八个里程碑式的版本之后&#xff08;M1~M8&#xff09;&#xff0c;Spring AI 1.0 正式版本&#xff0c;终于在 2025 年 5 月 20 日正式发布&#xff0c;这是另一个新高度的里程碑式的版本&#xff0c;标志着 Spring 生态系统正式全面拥抱人工智能…

Python实战:打造高效通讯录管理系统

&#x1f4cb; 编程基础第一期《8-30》–通讯录管理系统 &#x1f4d1; 项目介绍 在信息化时代&#xff0c;高效管理个人或团队联系人信息变得尤为重要。本文将带您实现一个基于Python的通讯录管理系统&#xff0c;该系统采用字典数据结构和JSON文件存储&#xff0c;实现了联系…

89. Java 数字和字符串 - Math 类深入解析

文章目录 89. Java 数字和字符串 - Math 类深入解析一、引言二、常量与基本方法2.1 Math 类常量2.2 绝对值和舍入绝对值方法舍入方法最小值和最大值 三、指数与对数方法四、三角函数方法五、总结 89. Java 数字和字符串 - Math 类深入解析 一、引言 在 Java 中&#xff0c;除…

STM32之SG90舵机控制(附视频讲解)

目录 前言&#xff1a; 一、硬件准备与接线 1.1 硬件清单 1.2 接线 二、 SG90舵机简介 1.1 外观 1.2 基本参数 1.3 引脚说明 1.4 控制原理 1.5 特点 1.6 常见问题 三、 单片机简介 四、 程序设计 4.1 定时器配置 4.2 角度控制函数 4.3 主函数调用 五、 总结 …

netstat命令Windows与Linux双平台

深入解析netstat命令:Windows与Linux双平台实战指南 netstat(Network Statistics)是网络诊断中最经典的工具之一,能够帮助用户查看网络连接、端口监听状态、路由表等信息。然而,Windows和Linux系统下的netstat在参数和输出格式上存在差异,容易让人混淆。本文将详细对比两…

攻防世界-ics-07

进入环境 进入项目管理 点击进行访问 是一堆代码进行审计 <?php session_start();if (!isset($_GET[page])) {show_source(__FILE__);die(); }if (isset($_GET[page]) && $_GET[page] ! index.php) {include(flag.php); }else {header(Location: ?pageflag.php);…

基于 Node.js 的 Express 服务是什么?

Express 是基于 ‌Node.js‌ 的一个轻量级、灵活的 Web 应用框架&#xff0c;用于快速构建 ‌HTTP 服务‌&#xff08;如网站、API 接口等&#xff09;&#xff0c;以下是详细解析&#xff1a; ‌一、Express 的核心作用‌ ‌简化 Node.js 原生开发‌ Node.js 原生 http 模块虽…

linux安装vscode以及配置vscode

vscode配置 1&#xff0c;准备工作2&#xff0c;VsCode安装插件3&#xff0c;cmake Tools 的使用 1&#xff0c;准备工作 所谓的准备工作&#xff0c;就是要让linux具备 vim gcc g编译器&#xff0c;可使用cmake&#xff0c;makefile等开发的条件。 首先我么以及有一个以安装好…

基于AI的智能农业病虫害识别系统实战指南

引言 在农业现代化进程中&#xff0c;病虫害防治始终是保障粮食安全的核心挑战。传统人工识别方式存在效率低、误判率高、响应滞后等问题。本文将通过完整的技术实现流程&#xff0c;展示如何利用Python生态构建智能病虫害识别系统&#xff0c;实现从图像采集到防治建议输出的…

【MySQL】第11节|MySQL 8.0 主从复制原理分析与实战(一)

一、MySQL主从复制基础 1. 核心概念 定义&#xff1a; MySQL主从复制是将主库&#xff08;Source/Master&#xff09;的数据变更同步到一个或多个从库&#xff08;Replica/Slave&#xff09;的机制&#xff0c;默认采用异步复制&#xff0c;支持全库、指定库或表的同步。 角…

【RabbitMQ】记录 InvalidDefinitionException: Java 8 date/time type

目录 1. 添加必要依赖 2. 配置全局序列化方案&#xff08;推荐&#xff09; 3. 配置RabbitMQ消息转换器 关键点说明 1. 添加必要依赖 首先确保项目中包含JSR-310支持模块&#xff1a; <dependency><groupId>com.fasterxml.jackson.datatype</groupId>&l…

【机器学习基础】机器学习入门核心算法:K-近邻算法(K-Nearest Neighbors, KNN)

机器学习入门核心算法&#xff1a;K-近邻算法&#xff08;K-Nearest Neighbors, KNN&#xff09; 一、算法逻辑1.1 基本概念1.2 关键要素距离度量K值选择 二、算法原理与数学推导2.1 分类任务2.2 回归任务2.3 时间复杂度分析 三、模型评估3.1 评估指标3.2 交叉验证调参 四、应用…

在h5端实现录音发送功能(兼容内嵌微信小程序) recorder-core

本文将通过一个实际的 Vue3 组件示例&#xff0c;带你一步步实现“按住录音&#xff0c;松开发送&#xff0c;上滑取消”的语音录制功能。 我们将使用强大且小巧的开源库 recorder-core&#xff0c;支持 MP3、WAV、AAC 等编码格式&#xff0c;兼容性较好。 &#x1f527; 项目…

深入掌握Node.js HTTP模块:从开始到放弃

文章目录 一、HTTP模块入门&#xff1a;从零搭建第一个服务器1.1 基础概念解析1.2 手把手创建服务器 二、核心功能深入解析2.1 处理不同请求类型2.2 实现文件下载功能 三、常见问题解决方案3.1 跨域问题处理3.2 防止服务崩溃3.3 调试技巧 四、安全最佳实践4.1 请求头安全设置4.…

SSM整合:Spring+SpringMVC+MyBatis完美融合实战指南

前言 在Java企业级开发领域&#xff0c;SSM&#xff08;SpringSpringMVCMyBatis&#xff09;框架组合一直占据着重要地位。这三个轻量级框架各司其职又相互配合&#xff0c;为开发者提供了高效、灵活的开发体验。本文将深入探讨SSM框架的整合过程&#xff0c;揭示整合背后的原…

[AI]大模型MCP快速入门及智能体执行模式介绍

[AI]大模型MCP快速入门及智能体执行模式介绍 一、MCP入门 介绍 MCP&#xff08;Model Context Protocol&#xff0c;模型上下文协议&#xff09;是一种由Anthropic公司于2024年提出的开放标准协议&#xff0c;旨在为大型语言模型&#xff08;LLM&#xff09;提供统一接口&am…