1. 程式人生 > >java上傳檔案通過SFTP

java上傳檔案通過SFTP

建立ChannelSftp物件,編寫一個工具類,根據ip,使用者名稱及密碼得到一個SFTP channel物件,即ChannelSftp的例項物件,在應用程式中就可以使用該物件來呼叫SFTP的各種操作方法。 SFTPChannel.java
SFTPChannel.java 

package com.longyg.sftp;

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

import org.apache.log4j.Logger;

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;

public class SFTPChannel {
    Session session = null;
    Channel channel = null;

    private static final Logger LOG = Logger.getLogger(SFTPChannel.class.getName());

    public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout) throws JSchException {

        String ftpHost = sftpDetails.get(SFTPConstants.SFTP_REQ_HOST);
        String port = sftpDetails.get(SFTPConstants.SFTP_REQ_PORT);
        String ftpUserName = sftpDetails.get(SFTPConstants.SFTP_REQ_USERNAME);
        String ftpPassword = sftpDetails.get(SFTPConstants.SFTP_REQ_PASSWORD);

        int ftpPort = SFTPConstants.SFTP_DEFAULT_PORT;
        if (port != null && !port.equals("")) {
            ftpPort = Integer.valueOf(port);
        }

        JSch jsch = new JSch(); // 建立JSch物件
        session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根據使用者名稱,主機ip,埠獲取一個Session物件
        LOG.debug("Session created.");
        if (ftpPassword != null) {
            session.setPassword(ftpPassword); // 設定密碼
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 為Session物件設定properties
        session.setTimeout(timeout); // 設定timeout時間
        session.connect(); // 通過Session建立連結
        LOG.debug("Session connected.");

        LOG.debug("Opening Channel.");
        channel = session.openChannel("sftp"); // 開啟SFTP通道
        channel.connect(); // 建立SFTP通道的連線
        LOG.debug("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
                + ", returning: " + channel);
        return (ChannelSftp) channel;
    }

    public void closeChannel() throws Exception {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}

SFTPConstants是一個靜態成員變數類:

SFTPConstans.java
SFTPConstants.java 

package com.longyg.sftp;

public class SFTPConstants {
    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";
}

檔案上傳,實現檔案上傳可以呼叫ChannelSftp物件的put方法。ChannelSftp中有12個put方法的過載方法: