SFTP上传下载

SFTP实现文件上传/下载功能
maven依赖:
    com.jcraft 0.1.55
    commons-io 2.6

文件传输协议: FTP、SFTP和SCP

package com.example.demo.ftp;

import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

/**
 * @Author: Andy.han
 * @Description: SFTPUtils {
 * <dependency>
 * <groupId>com.jcraft</groupId>
 * <artifactId>jsch</artifactId>
 * <version>0.1.55</version>
 * </dependency>
 * <dependency>
 * <groupId>commons-io</groupId>
 * <artifactId>commons-io</artifactId>
 * <version>2.6</version>
 * </dependency>
 * }
 * @Date: Created in 13:45 2019/5/30.
 * @Modified By:
 */

public class SFTPUtils {
    private transient Logger log = LoggerFactory.getLogger(this.getClass());

    private String logId;

    private ChannelSftp sftp;

    private Session session;
    /**
     * FTP 登录用户名
     */
    private String username;
    /**
     * FTP 登录密码
     */
    private String password;
    /**
     * 私钥
     */
    private String privateKey;
    /**
     * FTP 服务器地址IP地址
     */
    private String host;
    /**
     * FTP 端口
     */
    private int port;

    /**
     * @param username
     * @param password
     * @param host
     * @param port
     * @param logId
     * @Author: Andy.han
     * @Description: 构造基于密码认证的sftp对象
     * @Return: SFTPUtils
     * @Date: 2019/5/30 13:54
     */
    public SFTPUtils(String username, String password, String host, int port, String logId) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
        this.logId = logId;
    }

    /**
     * @param username
     * @param host
     * @param port
     * @param privateKey
     * @param logId
     * @Author: Andy.han
     * @Description: 构造基于秘钥认证的sftp对象
     * @Return: SFTPUtils
     * @Date: 2019/5/30 13:55
     */
    public SFTPUtils(String username, String host, int port, String privateKey, String logId) {
        this.username = username;
        this.host = host;
        this.port = port;
        this.privateKey = privateKey;
        this.logId = logId;
    }

    public SFTPUtils() {
    }

    /**
     * @param
     * @Author: Andy.han
     * @Description: 连接sftp服务器
     * @Return: void
     * @Date: 2019/5/30 13:56
     */
    public void login() {
        try {
            JSch jsch = new JSch();
            if (privateKey != null) {
                jsch.addIdentity(privateKey);// 设置私钥
                log.info("sftp connect,path of private key file:{}, logId:{}", privateKey, logId);
            }
            log.info("sftp connect by host:{} username:{}, logId:{}", host, username, logId);
            session = jsch.getSession(username, host, port);
            log.info("Session is build, logId:{}", logId);
            if (password != null) {
                session.setPassword(password);
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            log.info("Session is connected, logId:{}", logId);
            Channel channel = session.openChannel("sftp");
            channel.connect();
            log.info("channel is connected, logId:{}", logId);
            sftp = (ChannelSftp) channel;
            log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull, logId:{}", host, port, logId));
        } catch (JSchException e) {
            log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {} logId: {}", new Object[]{host, port, e.getMessage(), logId});
        }
    }

    /**
     * @param
     * @Author: Andy.han
     * @Description: 关闭连接 server
     * @Return: void
     * @Date: 2019/5/30 13:58
     */
    public void logout() {
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
                log.info("sftp is closed already, logId:{}", logId);
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
                log.info("sshSession is closed already, logId:{}", logId);
            }
        }
    }

    /**
     * @param directory    上传到该目录
     * @param sftpFileName sftp端文件名
     * @param input        输入流
     * @Author: Andy.han
     * @Description: 将输入流的数据上传到sftp作为文件
     * @Return: void
     * @Date: 2019/5/30 13:58
     */
    public void upload(String directory, String sftpFileName, InputStream input) throws SftpException {
        try {
            sftp.cd(directory);
        } catch (SftpException e) {
            log.warn("directory is not exist, logId:{}", logId);
            sftp.mkdir(directory);
            sftp.cd(directory);
        }
        sftp.put(input, sftpFileName);
        log.info("file:{} is upload successful, logId:{}", sftpFileName, logId);
    }

    /**
     * @param directory  上传到sftp目录
     * @param uploadFile 要上传的文件,包括路径
     * @throws FileNotFoundException
     * @throws SftpException
     * @Author: Andy.han
     * @Description: 上传单个文件
     * @Return: void
     * @Date: 2019/5/30 13:59
     */
    public void upload(String directory, String uploadFile, String fileName) throws FileNotFoundException, SftpException {
        File file = new File(uploadFile);
        upload(directory, fileName, new FileInputStream(file));
    }

    /**
     * @param directory    上传到sftp目录
     * @param sftpFileName 文件在sftp端的命名
     * @param byteArr      要上传的字节数组
     * @throws SftpException
     * @Author: Andy.han
     * @Description: 将byte[]上传到sftp,作为文件。注意:从String生成byte[]是,要指定字符集。
     * @Return: void
     * @Date: 2019/5/30 14:02
     */
    public void upload(String directory, String sftpFileName, byte[] byteArr) throws SftpException {
        upload(directory, sftpFileName, new ByteArrayInputStream(byteArr));
    }

    /**
     * @param directory    上传到sftp目录
     * @param sftpFileName 文件在sftp端的命名
     * @param dataStr      待上传的数据
     * @param charsetName  sftp上的文件,按该字符编码保存
     * @throws UnsupportedEncodingException
     * @throws SftpException
     * @Author: Andy.han
     * @Description: 将字符串按照指定的字符编码上传到sftp
     * @Return: void
     * @Date: 2019/5/30 14:03
     */
    public void upload(String directory, String sftpFileName, String dataStr, String charsetName) throws UnsupportedEncodingException, SftpException {
        upload(directory, sftpFileName, new ByteArrayInputStream(dataStr.getBytes(charsetName)));
    }

    /**
     * @param directory    下载目录
     * @param downloadFile 下载的文件
     * @param saveFile     存在本地的路径
     * @throws SftpException
     * @throws FileNotFoundException
     * @Author: Andy.han
     * @Description: 下载文件
     * @Return: void
     * @Date: 2019/5/30 14:05
     */
    public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
        if (directory != null && !"".equals(directory)) {
            sftp.cd(directory);
        }
        File file = new File(saveFile);
        sftp.get(downloadFile, new FileOutputStream(file));
        log.info("file:{} is download successful, logId:{}", downloadFile, logId);
    }

    /**
     * @param directory    下载目录
     * @param downloadFile 下载的文件名
     * @throws SftpException
     * @throws IOException
     * @Author: Andy.han
     * @Description: 下载文件
     * @Return: byte[]
     * @Date: 2019/5/30 14:06
     */
    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);
        log.info("file:{} is download successful, logId:{}", downloadFile, logId);
        return fileData;
    }

    /**
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     * @throws SftpException
     * @Author: Andy.han
     * @Description: 删除文件
     * @Return: void
     * @Date: 2019/5/30 14:07
     */
    public void delete(String directory, String deleteFile) throws SftpException {
        sftp.cd(directory);
        sftp.rm(deleteFile);
    }

    /**
     * @param directory
     * @throws SftpException
     * @Author: Andy.han
     * @Description: 列出目录下的文件
     * @Return: Vector<?>
     * @Date: 2019/5/30 14:08
     */
    public Vector<?> listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }

    public static void main(String[] args) throws Exception {
        SFTPUtils sftp = new SFTPUtils("****", "****", "****", 22, null);
        sftp.login();
        File file = new File("D:\\test.txt");
        InputStream is = new FileInputStream(file);
        sftp.upload("/home/SFTP/**/**/**/", "zj.txt", is);
        sftp.logout();

    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容