SFTP工具类

package com.sk.sbm.edge.utils;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;

/**

  • @Author :zsx

  • @Date:2020/7/9

  • @Description: sftp上传下载工具类
    */
    @Slf4j
    @Component
    public class SFTPUtil {
    @Value(" s f t p . h o s t " ) p r i v a t e S t r i n g h o s t ; @ V a l u e ( " {sftp.host}") private String host; @Value(" sftp.host")privateStringhost;@Value("{sftp.user-name}")
    private String username;
    @Value(" s f t p . p a s s w o r d " ) p r i v a t e S t r i n g p a s s w o r d ; @ V a l u e ( " {sftp.password}") private String password; @Value(" sftp.password")privateStringpassword;@Value("{sftp.port}")
    private int port = 22;
    private ChannelSftp sftp = null;
    private Session sshSession = null;

    public SFTPUtil(){

    }

    /**

    • @Author: zsx
    • @Description: sftp连接
    • @DateTime: 2020/7/9
    • @Params:
    • @Return
      */
      public void connect(){
      try{
      JSch jsch = new JSch();
      jsch.getSession(username,host,port);
      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 created.");
      Channel channel = sshSession.openChannel(“sftp”);
      channel.connect();
      log.info(“Opening Channel.”);
      sftp = (ChannelSftp)channel;
      log.info(“Connected to {}”,host);
      }catch(Exception e){
      log.error(“连接sftp服务器发生异常”,e);
      }
      }

    /**

    • @Author: zsx
    • @Description: 关闭连接
    • @DateTime: 2020/7/9
    • @Params:
    • @Return
      */
      public void disconnect(){
      if(sftp != null){
      if(sftp.isConnected()){
      sftp.disconnect();
      log.info(“sftp is closed already”);
      }
      }
      if(sshSession != null){
      if(sshSession.isConnected()){
      sshSession.disconnect();
      log.info(“sshSession is closed already”);
      }
      }
      }

    /**

    • 下载单个文件

    • @param remotePath:远程下载目录(以路径符号结束)

    • @param remoteFileName:下载文件名

    • @param localPath:本地保存目录(以路径符号结束)

    • @param localFileName:保存文件名

    • @return
      */
      public boolean downloadFile(String remotePath,String remoteFileName,String localPath,
      String localFileName){

      String filePath = remotePath + remoteFileName;
      File file = new File(localPath + localFileName);
      try( FileOutputStream fieloutput = new FileOutputStream(file)){
      sftpIsNull();

       sftp.get(filePath,fieloutput);
       log.info("---下载文件:【{}】成功,保存路径为:【{}】",filePath,localPath);
       return true;
      

      }catch(Exception e){
      //将本地流生成的临时文件删除掉
      file.delete();
      log.error(“下载文件发生异常,远端文件路径为【”+filePath+"】",e);
      }
      return false;
      }

    /**

    • 上传单个文件
    • @param remotePath:上传的路径
    • @param remoteFileName:保存的文件名
    • @param in:流
    • @return
    • @throws
      /
      public boolean uploadFile(String remotePath, String remoteFileName, InputStream in
      ) {
      try{
      sftpIsNull();
      if (this.sameFileExisted(remotePath,remoteFileName)){
      log.warn(“目录【{}】中已经存在文件【{}】上传失败”,remotePath,remoteFileName);
      return false;
      }
      String filePath = remotePath + remoteFileName;
      sftp.put(in,filePath);
      log.info(“文件【{}】上传成功”,filePath);
      return true;
      }catch(Exception e){
      log.error(“上传文件发生异常”,e);
      } finally{
      if(in != null){
      try{
      in.close();
      }catch(IOException e){
      log.error(“流关闭异常”,e);
      }
      }
      }
      return false;
      }
      /
      *
    • 列出目录下的文件
    • @param directory:要列出的目录
    • @param
    • @return
    • @throws SftpException
      */
      public Vector<ChannelSftp.LsEntry> listFiles(String directory) {
      try {
      sftpIsNull();
      if(!StringUtils.isEmpty(directory)){
      return sftp.ls(directory);
      }
      } catch (SftpException e) {
      log.error(“无法列出目录【”+directory+"】下的文件",e);
      }
      return null;
      }

    /**

    • @Author: zsx
    • @Description: 判断下是否有相同文件
    • @DateTime: 2020/7/9
    • @Params:
    • @Return
      */
      public boolean sameFileExisted(String dicrectory,String fileName){
      Vector<ChannelSftp.LsEntry> vector = this.listFiles(dicrectory);
      for (ChannelSftp.LsEntry entry : vector) {
      if(entry.getFilename().equals(fileName)){
      return true;
      }
      }
      return false;
      }

    /**

    • 删除stfp文件
    • @param directory:要删除文件所在目录
    • @param deleteFile:要删除的文件
    • @param
      */
      public void deleteSFTP(String directory,String deleteFile){
      try{
      sftpIsNull();
      sftp.rm(directory + deleteFile);
      log.info(“delete file success from sftp.”);
      }catch(Exception e){
      log.error(“sftp删除文件发生异常”,e);
      }
      }

    private void sftpIsNull(){
    if(sftp == null){
    throw new RuntimeException(“sftp实例为null”);
    }
    }

}
应用:
@Autowired
private SFTPUtil sftpUtil;
public Result uploadFile(MultipartFile file) {
//获取文件名称
String fileName = file.getName();
Result result = new Result();
if (StringUtils.isEmpty(fileName)) {
result.setStatus(Result.FILE_MISS_STATUS);
result.setMsg(“文件名不存在”);
} else {

        //拼接文件目录
        String fileDir = combineFileDir(fileName);
        result.setFileName(fileDir+fileName);
        log.info("文件上传的完整目录为【{}】",fileDir);
        try (InputStream in = file.getInputStream()) {
            //上传文件
            sftpUtil.connect();
            boolean upLoadResult = sftpUtil.uploadFile(fileDir,fileName,in);
            if (upLoadResult) {
                //上传成功
                result.setStatus(Result.SUCCESS_STATUS);
                result.setMsg("文件上传成功");
                result.setFileLength(file.getSize());
            } else {
                result.setStatus(Result.FAILURE_STATUS);
                result.setMsg("文件上传失败");
            }
        } catch (IOException e) {
            log.error("文件上传IO错误", e);
            result.setStatus(Result.FAILURE_STATUS);
            result.setMsg("文件上传IO错误!");
        }finally {
            sftpUtil.disconnect();
        }
    }
    return result;
}

@Override
public Result downloadFile(String fileName, String localPath) {
    sftpUtil.connect();
    Result result = new Result();
    if (StringUtils.isEmpty(fileName)) {
        result.setStatus(Result.FILE_MISS_STATUS);
        result.setMsg("文件名不存在");
    } else {

        try {
            String fileDir = this.combineFileDir(fileName);
            log.info("文件下载的完整路径为【{}】",fileDir);
            result.setFileName(fileDir+fileName);
            boolean downLoadResult = sftpUtil.downloadFile(fileDir,fileName,localPath,fileName);
            if (downLoadResult){
                result.setStatus(Result.SUCCESS_STATUS);
                result.setMsg("下载成功");
            }else{
                result.setStatus(Result.FAILURE_STATUS);
                result.setMsg("下载失败");
            }
        } catch (Exception e) {
            log.error("文件下载失败", e);
            result.setStatus(Result.FAILURE_STATUS);
            result.setMsg("下载失败");
        } finally {
            sftpUtil.disconnect();
        }
    }
    return result;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值