Java利用SFTP實現文件上傳與下載

SFTP是Secure File Transfer Protocol的縮寫,安全文件傳送協議。可以爲傳輸文件提供一種安全的加密方法。SFTP爲SSH的一部份,是一種傳輸文件到服務器的安全方式。

package sftp;

import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import org.apache.logging.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;

/**
 * Created by chenxl on 2018/3/8.
 */
public class SFTPUtils {

    private static final Logger LOG = org.apache.logging.log4j.LogManager.getLogger(SFTPUtils.class);

    private static final String host = "192.192.192.192";
    private static final int port = 22;
    private static final String username = "root";
    private static final String password = "root";
    public static final String directory = "/home";

    private static ChannelSftp sftp;

    private static SFTPUtils instance = null;

    private SFTPUtils() {
    }

    public static SFTPUtils getInstance() {
        if (instance == null) {
            if (instance == null) {
                instance = new SFTPUtils();
                sftp = instance.connect(host, port, username, password);   //獲取連接
            }
        }
        return instance;
    }

    /**
     * 連接sftp服務器
     *
     * @param host     主機
     * @param port     端口
     * @param username 用戶名
     * @param password 密碼
     * @return
     */
    public ChannelSftp connect(String host, int port, String username, String password) {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            Session sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            LOG.info("SFTP Session connected.");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            LOG.info("Connected to " + host);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
        return sftp;
    }

    /**
     * 上傳文件
     *
     * @param directory  上傳的目錄
     * @param uploadFile 要上傳的文件
     */
    public boolean upload(String directory, String uploadFile) {
        try {
            sftp.cd(directory);
            File file = new File(uploadFile);
            FileInputStream fileInputStream = new FileInputStream(file);
            sftp.put(fileInputStream, file.getName());
            fileInputStream.close();
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return false;
        }
    }

    /**
     * 下載文件
     *
     * @param directory    下載目錄
     * @param downloadFile 下載的文件
     * @param saveFile     存在本地的路徑
     */
    public File download(String directory, String downloadFile, String saveFile) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            sftp.get(downloadFile, fileOutputStream);
            fileOutputStream.close();
            return file;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return null;
        }
    }

    /**
     * 下載文件
     *
     * @param downloadFilePath 下載的文件完整目錄
     * @param saveFile     存在本地的路徑
     */
    public File download(String downloadFilePath, String saveFile) {
        try {
            int i = downloadFilePath.lastIndexOf('/');
            if (i == -1)
                return null;
            sftp.cd(downloadFilePath.substring(0, i));
            File file = new File(saveFile);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            sftp.get(downloadFilePath.substring(i + 1), fileOutputStream);
            fileOutputStream.close();
            return file;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return null;
        }
    }

    /**
     * 刪除文件
     *
     * @param directory  要刪除文件所在目錄
     * @param deleteFile 要刪除的文件
     */
    public void delete(String directory, String deleteFile) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
    }

    public void disconnect() {
        try {
            sftp.getSession().disconnect();
        } catch (JSchException e) {
            LOG.error(e.getMessage());
        }
        sftp.quit();
        sftp.disconnect();
    }

    /**
     * 列出目錄下的文件
     *
     * @param directory 要列出的目錄
     * @throws SftpException
     */
    public Vector<LsEntry> listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }

    public static void main(String[] args) throws IOException {
        SFTPUtils sf = SFTPUtils.getInstance();
//        sf.upload(directory, "C:\\Users\\hp\\Desktop\\123456.png");    //上傳文件

//        sf.download(directory, "2.png", "C:\\Users\\hp\\Desktop\\1212.png");
        File download = sf.download("/home/1.png", "C:\\Users\\hp\\Desktop\\122221.png");

//        sf.delete(directory, deleteFile); //刪除文件

        Vector<LsEntry> files = null;        //查看文件列表
        try {
            files = sf.listFiles(directory);
        } catch (SftpException e) {
            e.printStackTrace();
        }
        for (LsEntry file : files) {
            System.out.println("###\t" + file.getFilename());
        }
        sf.disconnect();
    }
}

用到的jar包maven依賴:

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
		<dependency>
			<groupId>com.jcraft</groupId>
			<artifactId>jsch</artifactId>
			<version>0.1.54</version>
		</dependency>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章