JSCH實現文件上傳下載至sftp服務器


  文件服務器采用FreeSSHd,文件服務器配置就不細說了。

  直接上代碼,該代碼可以直接使用。

  

import com.jcraft.jsch.*;

import java.io.InputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @author fc
 * @version V1.0
 * @Title SFTPConnect
 * @Package com.jsch
 * @Descript :TODO()
 * @date : 2018/8/30  下午3:50
 */
public class SftpConnect {
    private String user;
    private String password;
    private String host;
    private int port;
    private ChannelSftp channelSftp;
    private Session session;
    private Logger logger = LoggerFactory.getLogger(SftpConnect.class);
    private final String NO_SUCH_FILE = "No such file";

    public SftpConnect(String user, String password, String host, int port) {
        this.user = user;
        this.password = password;
        this.host = host;
        this.port = port;
    }

    private ChannelSftp connect(){
        JSch jSch=new JSch();
        try {
            session=jSch.getSession(user,host,port);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.setConfig(sshConfig);
            session.connect();
            channelSftp= (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();
        } catch (JSchException e) {
            return null;
        }
        return channelSftp;
    }

    /**
     * 斷開連接
     */
    private void disconnect() {
        channelSftp.disconnect();
        session.disconnect();
    }

    public boolean  upLoadFile(String path,String filename, InputStream is){
        if(channelSftp == null){
            logger.debug("初始化sftp連接:連接地址:{}",host);
            connect();
            logger.trace("sftp連接初始化完成:{}",host);
        }
        try {
            validatePath(path);
            channelSftp.put(is,filename);
            disconnect();
        } catch (SftpException e) {
            logger.error("文件上傳失敗:\n{}",e);
            return false;
        }
        return true;
    }

    

    /**
     * 驗證服務器文件夾路徑,如不存在則新建
     * @param path
     */
    private void validatePath(String path) throws SftpException {
        try {
            channelSftp.lstat(path);
            channelSftp.cd(path);
        } catch (SftpException e) {
            if(NO_SUCH_FILE.equals(e.getMessage())){
                logger.debug("{} 不存在,創建該路徑",path);
                String[] paths = path.split("/");
                for(String p : paths){
                    try {
                        channelSftp.cd(p);
                    } catch (SftpException e1) {
                        channelSftp.mkdir(p);
                        channelSftp.cd(p);
                    }
                }
            }else {
                throw e;
            }
        }
    }

    /**
     * 下載文件
     * @param path
     * @param filename
     * @param: is
     * @return
     */
    public InputStream  downFile(String path,String filename){
        if(channelSftp == null){
            logger.debug("初始化sftp連接:連接地址:{}",host);
            connect();
            logger.trace("sftp連接初始化完成:{}",host);
        }
        try {
            channelSftp.cd(path);
            InputStream is= channelSftp.get(filename);
            disconnect();
            return is;
        } catch (SftpException e) {
            return null;
        }
    }
}

 


免責聲明!

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



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