ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SFTP 工具类

2021-11-23 16:04:28  阅读:148  来源: 互联网

标签:String sftpPath param sftp remotePath import 工具 SFTP



import com.ai.frame.config.FtpConfig;
import com.ai.frame.config.SftpConfig;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SFTPUtils {

    private ChannelSftp sftp;
    private Session session;
    private String sftpPath;
    private Logger log = LoggerFactory.getLogger(SFTPUtils.class);

    public SFTPUtils(FtpConfig ftpConfig) {
        this.connectServer(ftpConfig.getFTP_ADDRESS(), Integer.parseInt(ftpConfig.getFTP_PORT()), ftpConfig.getFTP_USERNAME(), ftpConfig.getFTP_PASSWORD(), ftpConfig.getFTP_BASEPATH());
    }
    public SFTPUtils(SftpConfig sftpConfig) {
        this.connectServer(sftpConfig.getFtpHost(), Integer.parseInt(sftpConfig.getFtpPort()), sftpConfig.getFtpUserName(), sftpConfig.getFtpPassword(), sftpConfig.getSftpPath());
    }
    public SFTPUtils(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) {
        this.connectServer(ftpHost, ftpPort, ftpUserName, ftpPassword, sftpPath);
    }

    /**
     * 创建连接
     * @param ftpHost
     * @param ftpPort
     * @param ftpUserName
     * @param ftpPassword
     * @param sftpPath
     */
    private void connectServer(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) {
        try {
            this.sftpPath = sftpPath;
            // 创建JSch对象
            JSch jsch = new JSch();
            // 根据用户名,主机ip,端口获取一个Session对象
            session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
            if (StringUtils.isNotBlank(ftpPassword)) {
                // 设置密码
                session.setPassword(ftpPassword);
            }
            Properties configTemp = new Properties();
            configTemp.put("StrictHostKeyChecking", "no");
            // 为Session对象设置properties
            session.setConfig(configTemp);
            // 设置timeout时间
            session.setTimeout(60000);
            // 通过Session建立链接
            session.connect();
            // 打开SFTP通道
            sftp = (ChannelSftp) session.openChannel("sftp");
            // 建立SFTP通道的连接
            sftp.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开SFTP Channel、Session连接
     */
    public void closeChannel() {
        try {
            if (sftp != null) {
                sftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 本地上传文件
     *
     * @param localFile  本地文件
     * @param remotePath 远程文件
     * @param fileName   文件名称
     */
    public void upload(String localFile, String remotePath, String fileName) {
        try {
                remotePath = sftpPath + remotePath;
                createDir(remotePath);
                sftp.put(localFile, (remotePath + fileName), ChannelSftp.OVERWRITE);
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件流上传文件
     *
     * @param file       文件流
     * @param remotePath 远程目录
     * @param fileName   文件名称
     */
    public void upload(MultipartFile file, String remotePath, String fileName) {
        InputStream is = null;
        try {
            remotePath = sftpPath + remotePath;
            createDir(remotePath);
            is = file.getInputStream();
            sftp.put(is, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error(e.toString());
                }
            }
        }
    }

    /**
     * 下载文件
     *
     * @param remotePath 远程文件
     * @param fileName   文件名称
     * @param localFile  本地文件
     */
    public void download(String remotePath, String fileName, String localFile) {
        try {
            remotePath = sftpPath + remotePath;
            if (StringUtils.isNotBlank(remotePath)) {
                sftp.cd(remotePath);
            }
            sftp.get((remotePath + fileName), localFile);
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载文件
     *
     * @param remotePath 远程路径
  
     */
    public InputStream download(String remotePath, String fileName) {
        try {
            remotePath = sftpPath + remotePath;
            if (StringUtils.isNotBlank(remotePath)) {
                sftp.cd(remotePath);
            }
            return  sftp.get(fileName);
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 删除文件
     *
     * @param remotePath 要删除文件所在目录
     */
    public void delete(String remotePath) {
        try {
            if (StringUtils.isNotBlank(remotePath)) {
                remotePath = sftpPath + remotePath;
                sftp.rm(remotePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建一个文件目录
     */
    public void createDir(String createpath) {
        try {
            if (isDirExist(createpath)) {
                this.sftp.cd(createpath);
                return;
            }
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString())) {
                    sftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    sftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());
                }
            }
            this.sftp.cd(createpath);
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断目录是否存在
     */
    public boolean isDirExist(String directory) {
        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;
    }

}

标签:String,sftpPath,param,sftp,remotePath,import,工具,SFTP
来源: https://www.cnblogs.com/wxdnq/p/15593582.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有