SFTP文件的上傳、下載、刪除等操作

sftp工具類:

package 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.SftpException;


/** 
*  sftp工具類
*/
public class SFTPUtil {
    
    private transient Logger logger = LoggerFactory.getLogger(this.getClass());  
    
    private ChannelSftp sftp;  
        
    private Session session;  
    /** SFTP 登錄用戶名*/    
    private String username; 
    /** SFTP 登錄密碼*/    
    private String password;  
    /** 私鑰 */    
    private String privateKey;  
    /** SFTP 服務(wù)器地址IP地址*/    
    private String host;  
    /** SFTP 端口*/  
    private int port;  
        
    /**  
     * 構(gòu)造基于密碼認證的sftp對象  
     */    
    public SFTPUtil(String username, String password, String host, int port) {  
        this.username = username;  
        this.password = password;  
        this.host = host;  
        this.port = port;  
    } 
    
    /**  
     * 構(gòu)造基于秘鑰認證的sftp對象 
     */  
    public SFTPUtil(String username, String host, int port, String privateKey) {  
        this.username = username;  
        this.host = host;  
        this.port = port;  
        this.privateKey = privateKey;  
    }  
    
    public SFTPUtil(){}  
    
    
    /** 
     * 連接sftp服務(wù)器 
     */  
    public boolean connectSftp(){  
        try {  
            JSch jsch = new JSch();  
            if (privateKey != null) {  
                jsch.addIdentity(privateKey);// 設(shè)置私鑰  
            }  
    
            session = jsch.getSession(username, host, port);  
           
            if (password != null) {  
                session.setPassword(password);    
            }  
            Properties config = new Properties();  
            config.put("StrictHostKeyChecking", "no");  
                
            session.setConfig(config);  
            session.connect();  
              
            Channel channel = session.openChannel("sftp");  
            channel.connect();  
    
            sftp = (ChannelSftp) channel;  
            return true;
        } catch (JSchException e) { 
            logger.error("sftp鏈接異常:", e);
            return false;
        }  
    }    
    
    /** 
     * 關(guān)閉連接 server  
     */  
    public void close(){  
        if (sftp != null) {  
            if (sftp.isConnected()) {  
                sftp.disconnect();  
            }  
        }  
        if (session != null) {  
            if (session.isConnected()) {  
                session.disconnect();  
            }  
        }  
    }  

    
    /**  
     * 將輸入流的數(shù)據(jù)上傳到sftp作為文件
     * 
     * @param remotePath  sftp文件路徑
     * @param sftpFileName  sftp端文件名  
     * @param in   輸入流  
     */  
    public void upload(String remotePath, String sftpFileName, InputStream input) throws SftpException{  
        try {   
            sftp.cd(remotePath);
        } catch (SftpException e) { 
            //目錄不存在缀踪,則創(chuàng)建文件夾
            String [] dirs=remotePath.split(File.separator);
            String tempPath=remotePath;
            for(String dir:dirs){
                if(null== dir || "".equals(dir)) continue;
                tempPath+="/"+dir;
                try{ 
                    sftp.cd(tempPath);
                }catch(SftpException ex){
                    sftp.mkdir(tempPath);
                    sftp.cd(tempPath);
                }
            }
        }  
        sftp.put(input, sftpFileName);  //上傳文件
    } 
    

    /** 
     * 下載文件。
     * @param remotePath sftp文件路徑
     * @param downloadFile 下載的文件 
     * @param saveFile 存在本地的路徑 
     * @throws IOException  
     */    
    public void download(String saveFile, String remotePath, String fileName) throws Exception{  
        if (remotePath != null && !"".equals(remotePath)) {  
            sftp.cd(remotePath);  
        }  
        File file = new File(saveFile+File.separator+fileName);  
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        FileOutputStream out = new FileOutputStream(file);
        
        sftp.get(fileName, out); 
        
        if( out != null){
            out.close();
        }
    }  
    
    /**  
     * 下載文件 
     * @param directory 下載目錄 
     * @param downloadFile 下載的文件名 
     * @return 字節(jié)數(shù)組 
     */  
    public byte[] download(String directory, String downloadFile) throws SftpException, IOException{  
        if (directory != null && !"".equals(directory)) {  
            sftp.cd(directory);  
        }  
        InputStream is = sftp.get(downloadFile);  
          
        byte[] fileData = IOUtils.toByteArray(is);  
          
        return fileData;  
    }  
    
    
    /** 
     * 刪除文件 
     * @param directory 要刪除文件所在目錄 
     * @param deleteFile 要刪除的文件 
     */  
    public void delete(String directory, String deleteFile) throws SftpException{  
        sftp.cd(directory);  
        sftp.rm(deleteFile);  
    }  
    
    
    /** 
     * 列出目錄下的文件 
     * @param directory 要列出的目錄 
     * @param sftp 
     */  
    public Vector<?> listFiles(String directory) throws SftpException {  
        return sftp.ls(directory);  
    }  
    
      
    //上傳文件測試
    public static void main(String[] args) throws SftpException, IOException {  
        SFTPUtil sftp = new SFTPUtil("用戶名", "密碼", "ip地址", 22);  
//        sftp.login();  
        File file = new File("D:\\圖片\\t0124dd095ceb042322.jpg");  
        InputStream is = new FileInputStream(file);  
          
//        sftp.upload("基礎(chǔ)路徑","文件路徑", "test_sftp.jpg", is);  
        sftp.close();  
    }  
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末虹脯,一起剝皮案震驚了整個濱河市驴娃,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌循集,老刑警劉巖唇敞,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異咒彤,居然都是意外死亡疆柔,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門镶柱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來旷档,“玉大人,你說我怎么就攤上這事歇拆⌒” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵查吊,是天一觀的道長谐区。 經(jīng)常有香客問我,道長逻卖,這世上最難降的妖魔是什么宋列? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮评也,結(jié)果婚禮上炼杖,老公的妹妹穿的比我還像新娘灭返。我一直安慰自己,他們只是感情好坤邪,可當我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布熙含。 她就那樣靜靜地躺著,像睡著了一般艇纺。 火紅的嫁衣襯著肌膚如雪怎静。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天黔衡,我揣著相機與錄音蚓聘,去河邊找鬼。 笑死盟劫,一個胖子當著我的面吹牛夜牡,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播侣签,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼塘装,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了影所?” 一聲冷哼從身側(cè)響起蹦肴,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎型檀,沒想到半個月后冗尤,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體胀溺,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡裂七,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了仓坞。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片背零。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖无埃,靈堂內(nèi)的尸體忽然破棺而出徙瓶,到底是詐尸還是另有隱情,我是刑警寧澤嫉称,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布侦镇,位于F島的核電站,受9級特大地震影響织阅,放射性物質(zhì)發(fā)生泄漏壳繁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦颁督、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽嗅钻。三九已至皂冰,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間养篓,已是汗流浹背灼擂。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留觉至,地道東北人。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓睡腿,卻偏偏與公主長得像语御,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子席怪,可洞房花燭夜當晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容