远程连接SFTP进行文件上传、下载、删除等操作

第一步: 下载jar包   jsch-0.1.54.jar。

第二步:编写工具类进行相关操作。

  (1)连接远程SFTP

private static ChannelSftp connectSFTP(){

    String host = Constant.HOST;//sftp服务器ip

    String username = Constant.USERNAME;//用户名

    String password = Constant.PASSWORD;//密码

    int port = Constant.PORT;//默认的sftp端口号22

 

    JSch jsch = new JSch();

    Channel channel = null; 

    try {
      // 登录SSH
      session = jsch.getSession(username, host, port);
      if (StringUtils.isNotBlank(password)) {
        session.setPassword(password);
      }
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.setTimeout(10000);
      session.connect();
      // 打开SFTP
      channel = (ChannelSftp) session.openChannel("sftp");
      channel.connect();
      // 进行SFTP传输
      channel.put(localPath, remotePath, ChannelSftp.OVERWRITE);
    } catch (Exception e) {
      logger.error("SFTP上传发生错误", e);
      throw new RuntimeException(e);
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
      if (session != null) {
        session.disconnect();
      }
    }

    return channel;

  }

  (2)上传文件

/**

  * 上传文件

  * @param directory

  * 上传的目录

  * @param uploadFile

  * 要上传的文件

  * @param sftp

  */

  public void upload(String directory, String uploadFile, ChannelSftp sftp) {

    try {

      System.out.println(directory);

      sftp.cd(directory);

      System.out.println(uploadFile);

      File file = new File(uploadFile);

      System.out.println(directory+","+uploadFile);

      sftp.put(new FileInputStream(file), file.getName());

    } catch (Exception e) {

      System.out.println("upload:"+e);

    }

  }

  (3)下载文件

/**

  * 下载文件

  * @param directory

  * 下载目录

  * @param downloadFile

  * 下载的文件

  * @param saveFile

  * 存在本地的路径

  * @param sftp

  */

   public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {

    try {

       sftp.cd(directory);

       sftp.get(downloadFile,saveFile);

     } catch (Exception e) {

      System.out.println("download:"+e);

     }

  }

  (4)删除文件  

 /**

    * 删除文件

     * @param directory

    * 要删除文件所在目录

    * @param deleteFile

    * 要删除的文件

    * @param sftp

    */

  public void delete(String directory, String deleteFile, ChannelSftp sftp) {

    try {

      sftp.cd(directory);

      sftp.rm(deleteFile);

    } catch (Exception e) {

      System.out.println("delete:"+e);

    }

   }

  (5)删除期限外文件   

public List<String> clearSFTP(ChannelSftp sftp,String remotePath){
         //目录下所有文件集合
         List<String> list = new ArrayList<String>();
         //目录下所有文件名称集合
         List<String> fileNameList = new ArrayList<String>();
         //删除文件名集合
         List<String> dellist = new ArrayList<String>();
         SftpATTRS stat = null;  
      Vector ls = channel.ls(remotePath);
      for (Iterator it = ls.iterator(); it.hasNext();) {
        Object next = it.next();
        list.add(next.toString());
      }
      // 仅获取zip文件
      for (int i = 0; i < list.size(); i++) {
        if (list.get(i).endsWith(".zip")) {
          fileNameList.add(list.get(i).substring(
          list.get(i).lastIndexOf(" ") + 1));
        }
      }
      //循环遍历所有文件,删除超过期限文件
      for (String fname : fileNameList) {
        stat = channel.stat(remotePath +"/" +fname);
        if (CompairTime.compairTime(stat.getMtimeString(),delDays)) {
          dellist.add(fname);
          channel.rm(remotePath +"/" +fname);
        }
      }
    return dellist;
    }

CompairTime类如下(删除SFTP30天之前的文件)

package com.sinosoft.policyreg.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang.time.DateUtils;

public class CompairTime {

    public static boolean compairTime(String filetime,int delDays) throws ParseException {
        
        //SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        // 30天前的日期   用于比较
        Date orderdate = DateUtils.addDays(new Date(), delDays);
        
        //文件修改日期。
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        Date parse = sdf.parse(filetime);
        
        //parse 比 order早 则 true
        return parse.before(orderdate);
    }

}

完。。。

原文地址:https://www.cnblogs.com/gaofz/p/8509756.html