天天看點

關于Java使用SFTP實作檔案上傳下載下傳

直接上代碼:(代碼可以直接使用)

package com.lijy.util;  
  
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;  
import org.apache.log4j.Logger;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.util.Properties;  
  
public class FtpUtil {  
    /**log*/  
    protected static Logger log = Logger.getLogger(FtpUtil.class);  
  
    public static final String NO_FILE = "No such file";  
  
    private ChannelSftp sftp = null;  
  
    private Session sshSession = null;  
  
    private String username;  
  
    private String password;  
  
    private String host;  
  
    private int port;  
  
    public FtpUtil(String username, String password, String host, int port) {  
        this.username = username;  
        this.password = password;  
        this.host = host;  
        this.port = port;  
    }  
  
    /** 
     * 連接配接sftp伺服器 
     * @return ChannelSftp sftp類型 
     * @throws GoPayException 
     */  
    public ChannelSftp connect() throws GoPayException {  
        log.info("FtpUtil-->connect--ftp連接配接開始>>>>>>host=" + host + ">>>port" + port + ">>>username=" + username);  
        JSch jsch = new JSch();  
        try {  
            jsch.getSession(username, host, port);  
            sshSession = jsch.getSession(username, host, port);  
            log.info("ftp---Session created.");  
            sshSession.setPassword(password);  
            Properties properties = new Properties();  
            properties.put("StrictHostKeyChecking", "no");  
            sshSession.setConfig(properties);  
            sshSession.connect();  
            log.info("ftp---Session connected.");  
            Channel channel = sshSession.openChannel("sftp");  
            channel.connect();  
            log.info("Opening Channel.");  
            sftp = (ChannelSftp) channel;  
            log.info("ftp---Connected to " + host);  
        }  
        catch (JSchException e) {  
            throw new GoPayException("FtpUtil-->connect異常" + e.getMessage());  
        }  
        return sftp;  
    }  
  
    /** 
     * 載單個檔案 
     * @param directory       :遠端下載下傳目錄(以路徑符号結束) 
     * @param remoteFileName  FTP伺服器檔案名稱 如:xxx.txt ||xxx.txt.zip 
     * @param localFile       本地檔案路徑 如 D:\\xxx.txt 
     * @return 
     * @throws GoPayException 
     */  
    public File downloadFile(String directory, String remoteFileName,String localFile) throws GoPayException {  
        log.info(">>>>>>>>FtpUtil-->downloadFile--ftp下載下傳檔案"+remoteFileName+"開始>>>>>>>>>>>>>");  
        connect();  
        File file = null;  
        OutputStream output = null;  
        try {  
            file = new File(localFile);  
            if (file.exists()){  
                file.delete();  
            }  
            file.createNewFile();  
            sftp.cd(directory);  
            output = new FileOutputStream(file);  
            sftp.get(remoteFileName, output);  
            log.info("===DownloadFile:" + remoteFileName + " success from sftp.");  
        }  
        catch (SftpException e) {  
            if (e.toString().equals(NO_FILE)) {  
                log.info(">>>>>>>>FtpUtil-->downloadFile--ftp下載下傳檔案失敗" + directory +remoteFileName+ "不存在>>>>>>>>>>>>>");  
                throw new GoPayException("FtpUtil-->downloadFile--ftp下載下傳檔案失敗" + directory +remoteFileName + "不存在");  
            }  
            throw new GoPayException("ftp目錄或者檔案異常,檢查ftp目錄和檔案" + e.toString());  
        }  
        catch (FileNotFoundException e) {  
            throw new GoPayException("本地目錄異常,請檢查" + file.getPath() + e.getMessage());  
        }  
        catch (IOException e) {  
            throw new GoPayException("建立本地檔案失敗" + file.getPath() + e.getMessage());  
        }  
        finally {  
            if (output != null) {  
                try {  
                    output.close();  
                }  
                catch (IOException e) {  
                    throw new GoPayException("Close stream error."+ e.getMessage());  
                }  
            }  
            disconnect();  
        }  
  
        log.info(">>>>>>>>FtpUtil-->downloadFile--ftp下載下傳檔案結束>>>>>>>>>>>>>");  
        return file;  
    }  
  
    /** 
     * 上傳單個檔案 
     * @param directory      :遠端下載下傳目錄(以路徑符号結束) 
     * @param uploadFilePath 要上傳的檔案 如:D:\\test\\xxx.txt 
     * @param fileName       FTP伺服器檔案名稱 如:xxx.txt ||xxx.txt.zip 
     * @throws GoPayException 
     */  
    public void uploadFile(String directory, String uploadFilePath, String fileName)  
            throws GoPayException {  
        log.info(">>>>>>>>FtpUtil-->uploadFile--ftp上傳檔案開始>>>>>>>>>>>>>");  
        FileInputStream in = null;  
        connect();  
        try {  
            sftp.cd(directory);  
        }  
        catch (SftpException e) {  
            try {  
                sftp.mkdir(directory);  
                sftp.cd(directory);  
            }  
            catch (SftpException e1) {  
                throw new GoPayException("ftp建立檔案路徑失敗,路徑為" + directory);  
            }  
  
        }  
        File file = new File(uploadFilePath);  
        try {  
            in = new FileInputStream(file);  
            sftp.put(in, fileName);  
        }  
        catch (FileNotFoundException e) {  
            throw new GoPayException("檔案不存在-->" + uploadFilePath);  
        }  
        catch (SftpException e) {  
            throw new GoPayException("sftp異常-->" + e.getMessage());  
        }  
        finally {  
            if (in != null){  
                try {  
                    in.close();  
                }  
                catch (IOException e) {  
                    throw new GoPayException("Close stream error."+ e.getMessage());  
                }  
            }  
            disconnect();  
        }  
        log.info(">>>>>>>>FtpUtil-->uploadFile--ftp上傳檔案結束>>>>>>>>>>>>>");  
    }  
  
    private synchronized static File certTempEmptyile() {  
        String dirPath = SystemConfig.getProperty("down_settle_file.temp_path");  
        FileUtil.mkDir(dirPath);  
        String newFileName = System.currentTimeMillis() + ".txt";  
        String filePath = dirPath + File.separator + newFileName;  
        File file = new File(filePath);  
        return file;  
    }  
  
    /** 
     * 關閉連接配接 
     */  
    public void disconnect() {  
        if (this.sftp != null) {  
            if (this.sftp.isConnected()) {  
                this.sftp.disconnect();  
                this.sftp = null;  
                log.info("sftp is closed already");  
            }  
        }  
        if (this.sshSession != null) {  
            if (this.sshSession.isConnected()) {  
                this.sshSession.disconnect();  
                this.sshSession = null;  
                log.info("sshSession is closed already");  
            }  
        }  
    }  
  
}            

繼續閱讀