1. 程式人生 > 其它 >java實現連線 SFTP 上傳下載檔案

java實現連線 SFTP 上傳下載檔案

1、引入maven依賴

<!-- sftp -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>

2、程式碼實現如下

package com.test.sftp;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.util.*; /** * @author: void * @date: 2021-10-15 16:08 * @description: sftp伺服器檔案操作 * @version: 1.0 * */ @Slf4j public class SftpUtil { private String loginName = "sftp1"; private String loginPassword = "123456";
private String server = "192.169.2.15"; private Integer port = 22; public static void main(String[] args) { SftpUtil sftpUtil = new SftpUtil(); //上傳檔案 sftpUtil.uploadFile(); //下載檔案 sftpUtil.downloadFile(); //寫檔案 sftpUtil.writeFile();
//讀檔案 sftpUtil.readFile(); //刪除檔案 sftpUtil.deleteFile(); } /** * 連線登陸遠端伺服器 * * @return */ public ChannelSftp connect() { JSch jSch = new JSch(); Session session = null; ChannelSftp sftp = null; try { session = jSch.getSession(loginName, server, port); session.setPassword(loginPassword); session.setConfig(this.getSshConfig()); session.connect(); sftp = (ChannelSftp)session.openChannel("sftp"); sftp.connect(); log.error("結果:"+session.equals(sftp.getSession())); log.info("登入成功:" + sftp.getServerVersion()); } catch (Exception e) { log.error("SSH方式連線FTP伺服器時有JSchException異常!",e); return null; } return sftp; } /** * 獲取服務配置 * @return */ private Properties getSshConfig() { Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); return sshConfig; } /** * 關閉連線 * @param sftp */ public void disconnect(ChannelSftp sftp) { try { if(sftp!=null){ if(sftp.getSession().isConnected()){ sftp.getSession().disconnect(); } } } catch (Exception e) { log.error("關閉與sftp伺服器會話連線異常",e); } } /** * 下載遠端sftp伺服器檔案 * * @return */ public void downloadFile() { FileOutputStream output = null; ChannelSftp sftp = null; try { sftp = connect(); if(sftp == null){ return ; } //sftp伺服器上檔案路徑 String remoteFilename = "/test1/測試.txt"; //下載至本地路徑 File localFile = new File("./file/sftp/從sftp伺服器上下載.txt"); output = new FileOutputStream(localFile); sftp.get(remoteFilename, output); System.out.println("成功接收檔案,本地路徑:" + localFile.getAbsolutePath()); } catch (Exception e) { log.error("接收檔案異常!",e); } finally { try { if (null != output) { output.flush(); output.close(); } // 關閉連線 disconnect(sftp); } catch (IOException e) { log.error("關閉檔案時出錯!",e); } } } /** * 讀取遠端sftp伺服器檔案 * * @return */ public void readFile() { InputStream in = null; ArrayList<String> strings = new ArrayList<>(); ChannelSftp sftp = null; try { sftp = connect(); if(sftp == null){ return; } String remotePath = "/test1/"; String remoteFilename = "測試1.txt"; sftp.cd(remotePath); if(!listFiles(remotePath).contains(remoteFilename)){ log.error("no such file"); return; } in = sftp.get(remoteFilename); if (in != null) { BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf-8")); String str = null; while ((str = br.readLine()) != null) { System.out.println(str); } }else{ log.error("in為空,不能讀取。"); } } catch (Exception e) { log.error("接收檔案時異常!",e); } finally { try { if(in !=null){ in.close(); } // 關閉連線 disconnect(sftp); } catch (Exception e) { log.error("關閉檔案流時出現異常!",e); } } } /** * 寫檔案至遠端sftp伺服器 * * @return */ public void writeFile(){ ChannelSftp sftp = null; ByteArrayInputStream input = null; try { sftp = connect(); if(sftp == null){ return; } // 更改伺服器目錄 String remotePath = "/test1/"; sftp.cd(remotePath); // 傳送檔案 String remoteFilename = "寫檔案.txt"; String content = "測試內容"; input = new ByteArrayInputStream(content.getBytes()); sftp.put(input, remoteFilename); } catch (Exception e) { log.error("傳送檔案時有異常!",e); } finally { try { if (null != input) { input.close(); } // 關閉連線 disconnect(sftp); } catch (Exception e) { log.error("關閉檔案時出錯!",e); } } } /** * 上傳檔案至sftp伺服器 * @return */ public void uploadFile() { FileInputStream fis = null; ChannelSftp sftp = null; // 上傳檔案至伺服器此目錄 String remotePath = "./file/sftp/從sftp伺服器上下載.txt"; String remoteFilename = "/test1/上傳至sftp伺服器.txt"; try { sftp = connect(); if(sftp == null){ return ; } File localFile = new File(remotePath); fis = new FileInputStream(localFile); //傳送檔案 sftp.put(fis, remoteFilename); log.info("成功上傳檔案" ); } catch (Exception e) { log.error("上傳檔案時異常!",e); } finally { try { if (fis != null) { fis.close(); } // 關閉連線 disconnect(sftp); } catch (Exception e) { log.error("關閉檔案時出錯!",e); } } } /** * 遍歷遠端檔案 * * @param remotePath * @return * @throws Exception */ public List<String> listFiles(String remotePath){ List<String> ftpFileNameList = new ArrayList<String>(); ChannelSftp.LsEntry isEntity = null; String fileName = null; ChannelSftp sftp = null; try{ sftp = connect(); if(sftp == null){ return null; } Vector<ChannelSftp.LsEntry> sftpFile = sftp.ls(remotePath); Iterator<ChannelSftp.LsEntry> sftpFileNames = sftpFile.iterator(); while (sftpFileNames.hasNext()) { isEntity = (ChannelSftp.LsEntry) sftpFileNames.next(); fileName = isEntity.getFilename(); ftpFileNameList.add(fileName); } return ftpFileNameList; }catch (Exception e){ log.error("遍歷查詢sftp伺服器上檔案異常",e); return null; }finally { disconnect(sftp); } } /** * 刪除遠端檔案 * @return */ public void deleteFile() { boolean success = false; ChannelSftp sftp = null; try { sftp = connect(); if(sftp == null){ return; } String remotePath = "/test1/"; String remoteFilename = "limit.lua"; // 更改伺服器目錄 sftp.cd(remotePath); //判斷檔案是否存在 if(listFiles(remotePath).contains(remoteFilename)){ // 刪除檔案 sftp.rm(remoteFilename); log.info("刪除遠端檔案" + remoteFilename + "成功!"); } } catch (Exception e) { log.error("刪除檔案時有異常!",e); } finally { // 關閉連線 disconnect(sftp); } } }

相關內容

LINUX搭建SFTP伺服器

作者:小念 出處:https://www.cnblogs.com/kiko2014551511/ 本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,並保留此段宣告,否則保留追究法律責任的權利。