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
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/82592.shtml
英文地址,請注明出處:http://en.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…