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服務器


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM