最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java?項目連接并使用?SFTP?服務的示例詳解

 更新時間:2025年01月15日 11:39:09   作者:青燈文案  
SFTP是一種安全的文件傳輸協(xié)議,是SSH(Secure?Shell)協(xié)議的一個子協(xié)議,設計用于加密和保護文件傳輸?shù)陌踩?這篇文章主要介紹了Java?項目如何連接并使用?SFTP?服務的示例詳解,需要的朋友可以參考下

SFTP(Secure File Transfer Protocol)是一種安全的文件傳輸協(xié)議,是SSH(Secure Shell)協(xié)議的一個子協(xié)議,設計用于加密和保護文件傳輸?shù)陌踩?。SSH本身是一種網(wǎng)絡協(xié)議,用于在不安全的網(wǎng)絡中提供安全的遠程登錄和其他安全網(wǎng)絡服務。SFTP則在此基礎上,專注于文件的安全傳輸。

  • 加密傳輸:SFTP使用加密來保護傳輸?shù)臄?shù)據(jù),包括文件內(nèi)容和認證信息。
  • 身份驗證:SFTP使用SSH身份驗證機制來驗證用戶身份。用戶通常需要提供用戶名和密碼,或者使用SSH密鑰對進行身份驗證。
  • 文件和目錄操作:SFTP支持文件和目錄的上傳、下載、刪除、重命名和創(chuàng)建等操作。
  • 跨平臺兼容性:SFTP是一個跨平臺協(xié)議,可以在各種操作系統(tǒng)上使用,包括Linux、Unix、Windows等。
  • 端到端數(shù)據(jù)完整性:SFTP確保傳輸?shù)奈募谠春湍繕酥g的完整性,防止數(shù)據(jù)在傳輸過程中被篡改或損壞。
  • 可擴展性:SFTP可以與其他協(xié)議和安全機制一起使用,以增強其功能。例如,它可以與公鑰基礎設施(PKI)一起使用以實現(xiàn)更高級的安全性。

SFTP通常用于許多場景,包括遠程服務器維護、備份、文件共享和在不同計算機之間傳輸敏感數(shù)據(jù)。由于它提供了強大的安全性,因此特別適用于傳輸金融賬戶、公司文件和政府數(shù)據(jù)等敏感信息。

  • 端口:SFTP的默認端口與SSH相同,為22。這意味著只要sshd服務器啟動了,SFTP就可使用,不需要額外安裝。
  • 守護進程:SFTP本身沒有單獨的守護進程,它必須使用SSHD守護進程(端口號默認是22)來完成相應的連接操作。
  • 配置:SFTP的配置通常與SSH配置相關。例如,可以通過修改SSH配置文件(如sshd_config)來啟用或禁用SFTP功能,以及設置相關的訪問權限和安全策略。

SFTP結合了SSH的安全性和文件傳輸?shù)谋憬菪?,成為許多組織和個人在傳輸敏感數(shù)據(jù)時的首選協(xié)議。

一、常見注意事項

1、如果客戶端不支持 ssh-rsa 協(xié)議時,需要在登陸的時候添加屬性:

config.put("HostKeyAlgorithms", "+ssh-rsa");

…持續(xù)更新

二、添加第三方 pom 依賴

Java本身并不支持連接 SFTP,所以需要第三方依賴進行連接。

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

三、SFTPUtil 代碼

注意:如果客戶端不支持 ssh-rsa 協(xié)議時,需要添加屬性

package com.wen.util;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
/**
 * @author : rjw
 * @date : 2024-10-14
 */
public class SFTPUtil {
    private static final Logger logger = LoggerFactory.getLogger(SFTPUtil.class);
    private Session session;
    private ChannelSftp channelSftp;
	/**
	* 登錄
	*/
    public boolean login(String hostname, int port, String username, String password) {
        try {
            JSch jSch = new JSch();
            // 根據(jù)用戶名,IP地址獲取一個session對象。
            session = jSch.getSession(username, hostname, port);
            session.setPassword(password);
            // 避免第一次連接時需要輸入yes確認
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            logger.info("成功連接服務器");
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();
            logger.info("成功連接服務器");
            return true;
        } catch (JSchException e) {
            logger.error("SFTPUtil login file error:", e);
        }
        return false;
    }
	/**
	* 退出
	*/
    public void logout() {
        if (channelSftp != null && channelSftp.isConnected()) {
            try {
                channelSftp.disconnect();
                logger.info("成功退出 SFTP 服務器");
            } catch (Exception e) {
                logger.error("退出SFTP服務器異常: ", e);
            } finally {
                try {
                    channelSftp.disconnect(); // 關閉FTP服務器的連接
                } catch (Exception e) {
                    logger.error("關閉SFTP服務器的連接異常: ", e);
                }
            }
        }
        if (session != null && session.isConnected()) {
            try {
                session.disconnect();
                logger.info("成功退出 session 會話");
            } catch (Exception e) {
                logger.error("退出 session 會話異常: ", e);
            } finally {
                try {
                    session.disconnect(); // 關閉FTP服務器的連接
                } catch (Exception e) {
                    logger.error("關閉 session 會話的連接異常: ", e);
                }
            }
        }
    }
	/**
	* 判斷是否連接
	*/
    public boolean isConnected() {
        return channelSftp != null && channelSftp.isConnected();
    }
	/**
     * 上傳文件
     * 采用默認的傳輸模式:OVERWRITE
     *
     * @param src 輸入流(文件)
     * @param dst 上傳路徑
     * @param fileName 上傳文件名
     * @throws SftpException
     */
    public boolean upLoadFile(InputStream src, String dst, String fileName) throws SftpException {
        boolean isSuccess = false;
        try {
            if (createDir(dst)) {
                channelSftp.put(src, fileName);
                isSuccess = true;
            }
        } catch (SftpException e) {
            logger.error(fileName + "文件上傳異常", e);
        }
        return isSuccess;
    }
    /**
     * 創(chuàng)建一個文件目錄
     *
     * @param createPath 路徑
     * @return
     */
    public boolean createDir(String createPath) {
        boolean isSuccess = false;
        try {
            if (isDirExist(createPath)) {
                channelSftp.cd(createPath);
                return true;
            }
            String[] pathArray = createPath.split("/");
            StringBuilder filePath = new StringBuilder("/");
            for (String path : pathArray) {
                if (path.isEmpty()) {
                    continue;
                }
                filePath.append(path).append("/");
                if (isDirExist(filePath.toString())) {
                    channelSftp.cd(filePath.toString());
                } else {
                    // 建立目錄
                    channelSftp.mkdir(filePath.toString());
                    // 進入并設置為當前目錄
                    channelSftp.cd(filePath.toString());
                }
            }
            channelSftp.cd(createPath);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("目錄創(chuàng)建異常!", e);
        }
        return isSuccess;
    }
	/**
     * 判斷目錄是否存在
     *
     * @param directory 路徑
     * @return
     */
    public boolean isDirExist(String directory) {
        boolean isSuccess = false;
        try {
            SftpATTRS sftpATTRS = channelSftp.lstat(directory);
            isSuccess = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
        	logger.info("SFTPUtil path has error:{}", directory);
            logger.error("SFTPUtil path has error: ", e);
            if (e.getMessage().equalsIgnoreCase("no such file")) {
                isSuccess = false;
            }
        }
        return isSuccess;
    }
    /**
     * 重命名指定文件或目錄
     */
    public boolean rename(String oldPath, String newPath) {
        boolean isSuccess = false;
        try {
            channelSftp.rename(oldPath, newPath);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("重命名指定文件或目錄異常", e);
        }
        return isSuccess;
    }
    /**
     * 列出指定目錄下的所有文件和子目錄。
     */
    public Vector ls(String path) {
        try {
            Vector vector = channelSftp.ls(path);
            return vector;
        } catch (SftpException e) {
            logger.error("列出指定目錄下的所有文件和子目錄。", e);
        }
        return null;
    }
	/**
     * 刪除文件
     */
	public boolean deleteFile(String directory, String deleteFile) {
        boolean isSuccess = false;
        try {
            channelSftp.cd(directory);
            channelSftp.rm(deleteFile);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("刪除文件失敗", e);
        }
        return isSuccess;
    }
    /**
     * 下載文件
     *
     * @param directory 下載目錄
     * @param downloadFile 下載的文件
     * @param saveFile 下載到本地路徑
     */
    public boolean download(String directory, String downloadFile, String saveFile) {
        boolean isSuccess = false;
        try {
            channelSftp.cd(directory);
            File file = new File(saveFile);
            channelSftp.get(downloadFile, new FileOutputStream(file));
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("下載文件失敗", e);
        } catch (FileNotFoundException e) {
            logger.error("下載文件失敗", e);
        }
        return isSuccess;
    }
	/**
     * 輸出指定文件流
     */
	public InputStream getFile(String path) {
		try {
			InputStream inputStream = channelSftp.get(path);
			return inputStream;
		} catch (SftpException e) {
            throw new RuntimeException(e);
        }
	}
    /**
     * 下載文件,新
     */
    public InputStream downloadFile(String remoteFileName, String remoteFilePath) {
        InputStream input = null;
        try {
            if (!isDirExist(remoteFilePath)) {
                logger.info("SFTPUtil not changeWorkingDirectory.filename:{},Path:{}", remoteFileName, remoteFilePath);
                logout();
                return input;
            }
            logger.info("SFTPUtil Info filename:{},Path:{}", remoteFileName, remoteFilePath);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            channelSftp.get(remoteFileName, outputStream);
            input = new ByteArrayInputStream(outputStream.toByteArray());
            outputStream.close();
            logger.info("file download. filename:{},Path:{}", remoteFileName, remoteFilePath);
        } catch (Exception e) {
            logger.error("SFTPUtil download file error:", e);
            logout();
        }
        return input;
    }
	/**
     * 驗證sftp文件是否有效(判斷文件屬性的日期)
     */
    public String validateSourceData(String fileName, String remoteFilePath, Date nowTime) throws IOException, SftpException {
        Date temp = null;
        if (!isDirExist(remoteFilePath)) {
            logout();
            return "嘗試切換SFTP路徑失敗, 文件路徑: " + remoteFilePath + fileName;
        }
        Vector vector = channelSftp.ls(remoteFilePath);
        for (int i = 0; i < vector.capacity(); i++) {
            ChannelSftp.LsEntry data = (ChannelSftp.LsEntry) vector.get(i);
            if (data.getFilename().equalsIgnoreCase(fileName)) {
                temp = new Date(data.getAttrs().getMTime() * 1000L);
                //logger.info("時間: timeStamp:{},nowTime:{}",temp,nowTime);
                if (temp.getTime() == nowTime.getTime()) {
                    return "SFTP文件沒有更新";
                }
                nowTime.setTime(temp.getTime());
                break;
            }
        }
        //logout();
        return null;
    }
	/**
     * IP
     */
    public String getSFTPHost() {
        return session.getHost();
    }
	/**
     * 端口
     */
    public int getSFTPPort() {
        return session.getPort();
    }
}

四、測試示例

public class Test {
	private static SFTPUtil sftpUtil = new SFTPUtil();
	public static String convertInputStreamToString(InputStream inputStream) throws IOException{
        StringBuilder stringBuilder = new StringBuilder();
        try{
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null){
                System.out.println(line);
                stringBuilder.append(line).append("\n");
            }
        }catch (Exception e){
            System.out.println(e);
        }
        if(stringBuilder.length() > 0 && stringBuilder.charAt(stringBuilder.length() - 1) == '\n'){
            stringBuilder.setLength(stringBuilder.length() - 1);
        }
        return stringBuilder.toString();
    }
    public static void main(String[] args) {
        boolean connected = sftpUtil.isConnected();
        if (!connected) {
            System.out.println("連接SFTP");
            // 折里可以采用配置文件 @Value 注解
            connected = sftpUtil.login("10.26.73.163", 2222, "username", "password");
        }
        if (connected) {
            System.out.println("連接成功");
            System.out.println(sftpUtil.getSFTPHost() + " : " + sftpUtil.getSFTPPort());
            InputStream inputStream = sftpUtil.getFile("/rjw/wind.txt");
            String s = convertInputStreamToString(inputStream);
            System.out.println(s);
            File file = new File("C:\\Users\\wen\\Desktop\\sun.txt");
            InputStream inputStream1 = Files.newInputStream(file.toPath());
            boolean dir = sftpUtil.upLoadFile(inputStream1, "/rjw", "big.txt");
            System.out.println("添加文件成功: " + dir);
            sftpUtil.logout();
        }
    }
}

五、測試結果

到此這篇關于Java 項目如何連接并使用 SFTP 服務的示例詳解的文章就介紹到這了,更多相關Java使用 SFTP 服務內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • java.util.ArrayDeque類使用方法詳解

    java.util.ArrayDeque類使用方法詳解

    這篇文章主要介紹了java.util.ArrayDeque類使用方法,java.util.ArrayDeque類提供了可調整大小的陣列,并實現(xiàn)了Deque接口,感興趣的小伙伴們可以參考一下
    2016-03-03
  • slf4j與jul、log4j1、log4j2、logback的集成原理

    slf4j與jul、log4j1、log4j2、logback的集成原理

    這篇文章主要介紹了slf4j與jul、log4j1、log4j2、logback的集成原理,以及通用日志框架與具體日志實現(xiàn)系統(tǒng)的機制機制介紹,包括依賴的jar包,jar沖突處理等
    2022-03-03
  • 解決java攔截器獲取POST入?yún)е翤RequestBody參數(shù)丟失問題

    解決java攔截器獲取POST入?yún)е翤RequestBody參數(shù)丟失問題

    文章講述了在Java開發(fā)中使用攔截器獲取POST請求入?yún)r,由于流關閉導致`@RequestBody`參數(shù)丟失的問題,并提出了一種解決方案,解決方案包括自定義方法、防止流丟失、過濾器和攔截器的合理組織和使用,最終確保了參數(shù)的正確傳遞
    2024-11-11
  • Jaxb2實現(xiàn)JavaBean與xml互轉的方法詳解

    Jaxb2實現(xiàn)JavaBean與xml互轉的方法詳解

    這篇文章主要介紹了Jaxb2實現(xiàn)JavaBean與xml互轉的方法,簡單介紹了JAXB的概念、功能及實現(xiàn)JavaBean與xml互轉的具體操作技巧,需要的朋友可以參考下
    2017-04-04
  • 如何在Spring Boot項目中使用Spring AI

    如何在Spring Boot項目中使用Spring AI

    Spring AI是Spring框架中用于集成和使用人工智能和機器學習功能的組件,它提供了一種簡化的方式來與AI模型進行交互,這篇文章主要介紹了Spring Boot 在項目中使用Spring AI,需要的朋友可以參考下
    2024-05-05
  • Java實戰(zhàn)之飛翔的小鳥小游戲

    Java實戰(zhàn)之飛翔的小鳥小游戲

    這篇文章主要介紹了Java實戰(zhàn)之飛翔的小鳥小游戲,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • Java算法之BFS,DFS,動態(tài)規(guī)劃和貪心算法的實現(xiàn)

    Java算法之BFS,DFS,動態(tài)規(guī)劃和貪心算法的實現(xiàn)

    廣度優(yōu)先搜索(BFS)和深度優(yōu)先搜索(DFS)是圖遍歷算法中最常見的兩種算法,主要用于解決搜索和遍歷問題。動態(tài)規(guī)劃和貪心算法則用來解決優(yōu)化問題。本文就來看看這些算法的具體實現(xiàn)吧
    2023-04-04
  • SpringBoot動態(tài)導出word文檔實整教程(復制即可使用)

    SpringBoot動態(tài)導出word文檔實整教程(復制即可使用)

    在我們做項目的時候會需要把數(shù)據(jù)庫中的數(shù)據(jù)導出到word當中,下面這篇文章主要給大家介紹了關于SpringBoot動態(tài)導出word文檔實整教程的相關資料,文中的代碼復制即可使用,需要的朋友可以參考下
    2023-06-06
  • java Spring Boot 配置redis pom文件操作

    java Spring Boot 配置redis pom文件操作

    這篇文章主要介紹了java Spring Boot 配置redis pom文件操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • spring batch使用reader讀數(shù)據(jù)的內(nèi)存容量問題詳解

    spring batch使用reader讀數(shù)據(jù)的內(nèi)存容量問題詳解

    這篇文章主要介紹了spring batch使用reader讀數(shù)據(jù)的內(nèi)存容量問題詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-07-07

最新評論

客服| 介休市| 什邡市| 绩溪县| 敦煌市| 天全县| 若羌县| 姜堰市| 涟源市| 深州市| 读书| 开封市| 商城县| 茶陵县| 平舆县| 玉龙| 德令哈市| 惠安县| 邵阳市| 云阳县| 宜春市| 宿州市| 奉新县| 新源县| 乐业县| 东辽县| 同德县| 镇坪县| 龙岩市| 墨玉县| 铜川市| 和平县| 邵阳县| 高清| 新乡市| 东丽区| 广东省| 沿河| 武平县| 合江县| 白银市|