使用Jsch實現(xiàn)Sftp文件下載-支持?jǐn)帱c續(xù)傳和進(jìn)程監(jiān)控 參考鏈接:

參考鏈接
API: https://epaul.github.io/jsch-documentation/javadoc/

文件下載

public static void downloadFile(String src, String dst,
                                  Map<String, String> sftpDetails) throws Exception{
        SftpUtil sftpUtil = new SftpUtil();
        ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 160000);
        try {
            //此處演示 斷點續(xù)傳,下方完整代碼中有其他方式
            chSftp.get(src, dst, new MyProgressMonitor(),ChannelSftp.RESUME); //斷點續(xù)傳
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            chSftp.quit();
            sftpUtil.closeChannel();
        }
    }

測試斷點續(xù)傳

 public static void main(String[] arg) throws Exception {
        // 設(shè)置主機(jī)ip,端口,用戶名,密碼
        Map<String, String> sftpDetails = new HashMap<String, String>();
        sftpDetails.put(SFTP_REQ_HOST, "192.9.198.214");
        sftpDetails.put(SFTP_REQ_USERNAME, "sftp-user");
        sftpDetails.put(SFTP_REQ_PASSWORD, "sa");
        sftpDetails.put(SFTP_REQ_PORT, "22");

        //測試文件上傳
        String src = "C:\\xxx\\TMP\\site-1.10.4.zip"; // 本地文件名
        String dst = "/tmp/sftp/"; // 目標(biāo)文件名
        uploadFile(src, dst, sftpDetails);

        //測試文件下載
        String srcFilename = "/tmp/sftp/site-1.10.4.zip";
        String dstFilename = "C:\\tmp\\site-1.10.4-new.zip";
        downloadFile(srcFilename, dstFilename, sftpDetails);

    }

[圖片上傳失敗...(image-27c442-1530930487193)][圖片上傳失敗...(image-6b09e6-1530930487193)]


完整程序

package com.feisherlpf.sftpdemo.SFTPUtil;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpProgressMonitor;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by feisher(lpf) on 2018/7/7.
 */

public class SftpUtil {
    Session session = null;
    Channel channel = null;
    public static final String SFTP_REQ_HOST = "host";
    public static final String SFTP_REQ_PORT = "port";
    public static final String SFTP_REQ_USERNAME = "username";
    public static final String SFTP_REQ_PASSWORD = "password";
    public static final int SFTP_DEFAULT_PORT = 22;
    public static final String SFTP_REQ_LOC = "location";
    /**
     * 測試程序
     * @param arg
     * @throws Exception
     */
    public static void main(String[] arg) throws Exception {
        // 設(shè)置主機(jī)ip,端口,用戶名,密碼
        Map<String, String> sftpDetails = new HashMap<String, String>();
        sftpDetails.put(SFTP_REQ_HOST, "192.9.198.214");
        sftpDetails.put(SFTP_REQ_USERNAME, "sftp-user");
        sftpDetails.put(SFTP_REQ_PASSWORD, "sa");
        sftpDetails.put(SFTP_REQ_PORT, "22");

        //測試文件上傳
        String src = "C:\\xxx\\TMP\\site-1.10.4.zip"; // 本地文件名
        String dst = "/tmp/sftp/"; // 目標(biāo)文件名
        uploadFile(src, dst, sftpDetails);

        //測試文件下載
        String srcFilename = "/tmp/sftp/site-1.10.4.zip";
        String dstFilename = "C:\\tmp\\site-1.10.4-new.zip";
        downloadFile(srcFilename, dstFilename, sftpDetails);

    }

    public static void downloadFile(String src, String dst,
                                  Map<String, String> sftpDetails) throws Exception{
        SftpUtil sftpUtil = new SftpUtil();
        ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 160000);
        // Retrieves the file attributes of a file or directory
        // SftpATTRS attr = chSftp.stat(src);
        // long fileSize = attr.getSize();
        //代碼段1/代碼段2/代碼段3:分別演示了如何使用JSch的各種put方法來進(jìn)行文件下載
        try {
            // 代碼段1:使用這個方法時,dst可以是目錄,若dst為目錄,則下載到本地的文件名將與src文件名相同
            chSftp.get(src, dst, new MyProgressMonitor(),ChannelSftp.RESUME); //斷點續(xù)傳
            /***
             OutputStream out = new FileOutputStream(dst);
             // 代碼段2:將目標(biāo)服務(wù)器上文件名為src的文件下載到本地的一個輸出流對象,該輸出流為一個文件輸出流
             chSftp.get(src, out, new MyProgressMonitor());

             // 代碼段3:采用讀取get方法返回的輸入流數(shù)據(jù)的方式來下載文件
             InputStream is = chSftp.get(src, new MyProgressMonitor(),ChannelSftp.RESUME);
             byte[] buff = new byte[1024 * 2];
             int read;
             if (is != null) {
             do {
             read = is.read(buff, 0, buff.length);
             if (read > 0) {
             out.write(buff, 0, read);
             }
             out.flush();
             } while (read >= 0);
             }
             **/

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            chSftp.quit();
            sftpUtil.closeChannel();
        }
    }

    public static void uploadFile(String src, String dst,
                                  Map<String, String> sftpDetails) throws Exception {
        SftpUtil sftpUtil = new SftpUtil();
        ChannelSftp chSftp = sftpUtil.getChannel(sftpDetails, 60000);
        /**
         * 代碼段1/代碼段2/代碼段3分別演示了如何使用JSch的不同的put方法來進(jìn)行文件上傳。這三段代碼實現(xiàn)的功能是一樣的,
         * 都是將本地的文件src上傳到了服務(wù)器的dst文件
         */
        /**代碼段1
         OutputStream out = chSftp.put(dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 使用OVERWRITE模式
         byte[] buff = new byte[1024 * 256]; // 設(shè)定每次傳輸?shù)臄?shù)據(jù)塊大小為256KB
         int read;
         if (out != null) {
         InputStream is = new FileInputStream(src);
         do {
         read = is.read(buff, 0, buff.length);
         if (read > 0) {
         out.write(buff, 0, read);
         }
         out.flush();
         } while (read >= 0);
         }
         **/

        // 使用這個方法時,dst可以是目錄,當(dāng)dst是目錄時,上傳后的目標(biāo)文件名將與src文件名相同
        // ChannelSftp.RESUME:斷點續(xù)傳
        chSftp.put(src, dst, new MyProgressMonitor(), ChannelSftp.RESUME); // 代碼段2
        // 將本地文件名為src的文件輸入流上傳到目標(biāo)服務(wù)器,目標(biāo)文件名為dst。
        // chSftp.put(new FileInputStream(src), dst,new MyProgressMonitor2(), ChannelSftp.OVERWRITE); // 代碼段3

        chSftp.quit();
        sftpUtil.closeChannel();
    }
    /**
     * 根據(jù)ip,用戶名及密碼得到一個SFTP
     * channel對象,即ChannelSftp的實例對象,在應(yīng)用程序中就可以使用該對象來調(diào)用SFTP的各種操作方法
     *
     * @param sftpDetails
     * @param timeout
     * @return
     * @throws JSchException
     */
    public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout)
            throws JSchException {
        String ftpHost = sftpDetails.get(SFTP_REQ_HOST);
        String port = sftpDetails.get(SFTP_REQ_PORT);
        String ftpUserName = sftpDetails.get(SFTP_REQ_USERNAME);
        String ftpPassword = sftpDetails.get(SFTP_REQ_PASSWORD);
        int ftpPort = SFTP_DEFAULT_PORT;
        if (port != null && !port.equals("")) {
            ftpPort = Integer.valueOf(port);
        }
        JSch jsch = new JSch(); // 創(chuàng)建JSch對象
        session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根據(jù)用戶名,主機(jī)ip,端口獲取一個Session對象
        if (ftpPassword != null) {
            session.setPassword(ftpPassword); // 設(shè)置密碼
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 為Session對象設(shè)置properties
        session.setTimeout(timeout); // 設(shè)置timeout時間
        session.connect(5000); // 通過Session建立鏈接
        channel = session.openChannel("sftp"); // 打開SFTP通道
        channel.connect(); // 建立SFTP通道的連接
        return (ChannelSftp) channel;
    }
    public void closeChannel() throws Exception {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
    /**
     * 進(jìn)度監(jiān)控器-JSch每次傳輸一個數(shù)據(jù)塊,就會調(diào)用count方法來實現(xiàn)主動進(jìn)度通知
     *
     */
    public static class MyProgressMonitor implements SftpProgressMonitor {
        private long count = 0;     //當(dāng)前接收的總字節(jié)數(shù)
        private long max = 0;       //最終文件大小
        private long percent = -1;  //進(jìn)度
        /**
         * 當(dāng)每次傳輸了一個數(shù)據(jù)塊后,調(diào)用count方法,count方法的參數(shù)為這一次傳輸?shù)臄?shù)據(jù)塊大小
         */
        @Override
        public boolean count(long count) {
            this.count += count;
            if (percent >= this.count * 100 / max) {
                return true;
            }
            percent = this.count * 100 / max;
            System.out.println("Completed " + this.count + "(" + percent
                    + "%) out of " + max + ".");
            return true;
        }
        /**
         * 當(dāng)傳輸結(jié)束時,調(diào)用end方法
         */
        @Override
        public void end() {
            System.out.println("Transferring done.");
        }
        /**
         * 當(dāng)文件開始傳輸時,調(diào)用init方法
         */
        @Override
        public void init(int op, String src, String dest, long max) {
            if (op==SftpProgressMonitor.PUT) {
                System.out.println("Upload file begin.");
            }else {
                System.out.println("Download file begin.");
            }

            this.max = max;
            this.count = 0;
            this.percent = -1;
        }
    }

}

參考鏈接

https://www.cnblogs.com/ssslinppp/p/6249264.html

API: https://epaul.github.io/jsch-documentation/javadoc/

官方Demo:http://www.jcraft.com/jsch/examples/Sftp.java

http://www.jcraft.com/jsch/examples/Sftp.java.html

http://www.jcraft.com/jsch/examples/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容