使用Jsch實現(xiàn)Sftp文件下載-支持斷點續(xù)傳和進程監(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è)置主機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/"; // 目標文件名
        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è)置主機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/"; // 目標文件名
        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方法來進行文件下載
        try {
            // 代碼段1:使用這個方法時梧田,dst可以是目錄,若dst為目錄稚虎,則下載到本地的文件名將與src文件名相同
            chSftp.get(src, dst, new MyProgressMonitor(),ChannelSftp.RESUME); //斷點續(xù)傳
            /***
             OutputStream out = new FileOutputStream(dst);
             // 代碼段2:將目標服務(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方法來進行文件上傳。這三段代碼實現(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可以是目錄,當dst是目錄時寻拂,上傳后的目標文件名將與src文件名相同
        // ChannelSftp.RESUME:斷點續(xù)傳
        chSftp.put(src, dst, new MyProgressMonitor(), ChannelSftp.RESUME); // 代碼段2
        // 將本地文件名為src的文件輸入流上傳到目標服務(wù)器程奠,目標文件名為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ù)用戶名慌核,主機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();
        }
    }
    /**
     * 進度監(jiān)控器-JSch每次傳輸一個數(shù)據(jù)塊,就會調(diào)用count方法來實現(xiàn)主動進度通知
     *
     */
    public static class MyProgressMonitor implements SftpProgressMonitor {
        private long count = 0;     //當前接收的總字節(jié)數(shù)
        private long max = 0;       //最終文件大小
        private long percent = -1;  //進度
        /**
         * 當每次傳輸了一個數(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;
        }
        /**
         * 當傳輸結(jié)束時,調(diào)用end方法
         */
        @Override
        public void end() {
            System.out.println("Transferring done.");
        }
        /**
         * 當文件開始傳輸時扒接,調(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)系作者
  • 序言:七十年代末伪货,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子钾怔,更是在濱河造成了極大的恐慌碱呼,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件宗侦,死亡現(xiàn)場離奇詭異愚臀,居然都是意外死亡,警方通過查閱死者的電腦和手機矾利,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門姑裂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人男旗,你說我怎么就攤上這事舶斧。” “怎么了察皇?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵茴厉,是天一觀的道長泽台。 經(jīng)常有香客問我,道長矾缓,這世上最難降的妖魔是什么怀酷? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮嗜闻,結(jié)果婚禮上蜕依,老公的妹妹穿的比我還像新娘。我一直安慰自己琉雳,他們只是感情好笔横,可當我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著咐吼,像睡著了一般吹缔。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上锯茄,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天厢塘,我揣著相機與錄音,去河邊找鬼肌幽。 笑死晚碾,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的喂急。 我是一名探鬼主播格嘁,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼廊移!你這毒婦竟也來了糕簿?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤狡孔,失蹤者是張志新(化名)和其女友劉穎懂诗,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體苗膝,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡殃恒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了辱揭。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片离唐。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖问窃,靈堂內(nèi)的尸體忽然破棺而出亥鬓,到底是詐尸還是另有隱情,我是刑警寧澤泡躯,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布贮竟,位于F島的核電站,受9級特大地震影響较剃,放射性物質(zhì)發(fā)生泄漏咕别。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一写穴、第九天 我趴在偏房一處隱蔽的房頂上張望惰拱。 院中可真熱鬧,春花似錦啊送、人聲如沸偿短。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽昔逗。三九已至,卻和暖如春篷朵,著一層夾襖步出監(jiān)牢的瞬間勾怒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工声旺, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留笔链,地道東北人。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓腮猖,卻偏偏與公主長得像鉴扫,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子澈缺,可洞房花燭夜當晚...
    茶點故事閱讀 45,691評論 2 361