SFTP工具类

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

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

@Slf4j
public class SFTP {
    /**
     * 将文件上传到服务器
     *
     * @param filePath    文件路径
     * @param channelSftp channelSftp对象
     * @return
     */
    public static boolean uploadFile(String uploadPath, String filePath, ChannelSftp channelSftp) {
        OutputStream outstream = null;
        InputStream instream = null;
        boolean successFlag = false;
        try {
            log.info("<<==========uploadPath" + uploadPath);
            log.info("<<==========filePath" + filePath);
            createDir(uploadPath, channelSftp);
            File isfile = new File(filePath);
            log.info("<<==========判断文件是否存在");
            if (isfile.isFile()) {
                log.info("<<==========文件存在");
                outstream = channelSftp.put(isfile.getName());
                File file = new File(filePath);
                if (file.exists()) {
                    log.info("<<==========开始写入文件");
                    instream = new FileInputStream(file);
                    byte b[] = new byte[1024];
                    int n;
                    while ((n = instream.read(b)) != -1) {
                        outstream.write(b, 0, n);
                    }
                    outstream.flush();
                }
                successFlag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
                if (outstream != null) {
                    outstream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return successFlag;
    }

    public static Session initJschSession(String ftpUserName, String ftpPassword, String ftpHost, int ftpPort) throws JSchException {
        String privateKey = ""; //
        String passphrase = "";
        JSch jsch = new JSch(); // 创建JSch对象
        if (StringUtils.isNotBlank(privateKey) && StringUtils.isNotBlank(passphrase)) {
            jsch.addIdentity(privateKey, passphrase);
        }
        if (StringUtils.isNotBlank(privateKey) && StringUtils.isBlank(passphrase)) {
            jsch.addIdentity(privateKey);
        }
        jsch.getSession(ftpUserName, ftpHost, ftpPort);
        Session session = jsch.getSession(ftpUserName, ftpHost, ftpPort); // 根据用户名,主机ip,端口获取一个Session对象
        if (StringUtils.isNotBlank(ftpPassword)) {
            session.setPassword(ftpPassword); // 设置密码
        }
        return session;
    }

    /**
     * 获取ChannelSftp链接
     *
     * @param timeout 超时时间
     * @return 返回ChannelSftp对象
     * @throws JSchException
     */
    public static ChannelSftp getChannelSftp(Session session, int timeout) throws JSchException {
        Channel channel = null;
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config); // 为Session对象设置properties
        session.setTimeout(timeout); // 设置timeout时间
        session.connect(); // 通过Session建立链接
        channel = session.openChannel("sftp"); // 打开SFTP通道
        channel.connect(); // 建立SFTP通道的连接
        return (ChannelSftp) channel;
    }

    /**
     * 断开sftp链接
     *
     * @param session 会话
     * @param channel 通道
     */
    public static void closeConnection(Channel channel, Session session) {
        try {
            if (session != null) {
                session.disconnect(); //关闭session链接
            }
            if (channel != null) {
                channel.disconnect(); //断开连接
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建目录
     *
     * @param createpath
     * @return
     */
    public static boolean createDir(String createpath, ChannelSftp sftp) {
        try {
            log.info("<<==========判断文件夹是否存在");
            if (isDirExist(createpath, sftp)) {
                sftp.cd(createpath);
                return true;
            }
            log.info("<<==========文件夹不存在,创建文件夹");
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString(), sftp)) {
                    sftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    sftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());
                }
            }
            sftp.cd(createpath);
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断目录是否存在
     *
     * @param directory
     * @return
     */
    public static boolean isDirExist(String directory, ChannelSftp sftp) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值