sftp批量上传及批量下载等最全功能的工具类SFTPUtils

Posted 阿啄debugIT

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sftp批量上传及批量下载等最全功能的工具类SFTPUtils相关的知识,希望对你有一定的参考价值。

sftp批量上传及批量下载等最全功能的工具类

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
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 java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SFTPUtils

  private static final Logger log = LoggerFactory.getLogger(SFTPUtils.class);
  private String host;
  private String username;
  private String password;
  private int port = 22;
  private ChannelSftp sftp = null;
  private Session sshSession = null;

  public SFTPUtils() 
  

  public SFTPUtils(String host, String username, String password) 
    this.host = host;
    this.username = username;
    this.password = password;
  

  public SFTPUtils(String host, int port, String username, String password) 
    this.host = host;
    this.username = username;
    this.password = password;
    this.port = port;
  

  public boolean connect()
  
    try
    
      JSch jsch = new JSch();
      jsch.getSession(this.username, this.host, this.port);
      this.sshSession = jsch.getSession(this.username, this.host, this.port);
      if (log.isInfoEnabled()) 
        log.info("Session created.");
      
      this.sshSession.setPassword(this.password);
      Properties sshConfig = new Properties();
      sshConfig.put("StrictHostKeyChecking", "no");
      this.sshSession.setConfig(sshConfig);
      this.sshSession.connect();
      if (log.isInfoEnabled()) 
        log.info("Session connected.");
      
      Channel channel = this.sshSession.openChannel("sftp");
      channel.connect();
      if (log.isInfoEnabled()) 
        log.info("Opening Channel.");
      
      this.sftp = ((ChannelSftp)channel);
      if (log.isInfoEnabled()) 
        log.info("Connected to " + this.host + ".");
      
      return true;
     catch (JSchException e) 
      log.error(new Date() + "连接sftp出现异常如下:");
      e.printStackTrace();
    return false;
  

  public void disconnect()
  
    if ((this.sftp != null) && 
      (this.sftp.isConnected())) 
      this.sftp.disconnect();
      if (log.isInfoEnabled()) 
        log.info("sftp is closed already");
      
    

    if ((this.sshSession != null) && 
      (this.sshSession.isConnected())) 
      this.sshSession.disconnect();
      if (log.isInfoEnabled())
        log.info("sshSession is closed already");
    
  

  public List<String> batchDownLoadFile(String remotePath, String localPath, String fileFormat, String fileEndFormat, boolean del)
  
    List filenames = new ArrayList();
    if (connect()) 
      try 
        Vector v = listFiles(remotePath);
        if (v.size() > 0) 
          log.info("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
          Iterator it = v.iterator();
          while (it.hasNext()) 
            ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry)it.next();
            String filename = entry.getFilename();
            SftpATTRS attrs = entry.getAttrs();
            if (!attrs.isDir()) 
              boolean flag = false;
              String localFileName = localPath + filename;
              fileFormat = fileFormat == null ? "" : fileFormat.trim();
              fileEndFormat = fileEndFormat == null ? "" : fileEndFormat.trim();

              if ((fileFormat.length() > 0) && (fileEndFormat.length() > 0)) 
                if ((filename.startsWith(fileFormat)) && (filename.endsWith(fileEndFormat))) 
                  flag = downloadFile(remotePath, filename, localPath, filename);
                  if (flag) 
                    filenames.add(localFileName);
                    if ((flag) && (del))
                      deleteSFTP(remotePath, filename);
                  
                
              
              else if ((fileFormat.length() > 0) && ("".equals(fileEndFormat))) 
                if (filename.startsWith(fileFormat)) 
                  flag = downloadFile(remotePath, filename, localPath, filename);
                  if (flag) 
                    filenames.add(localFileName);
                    if ((flag) && (del))
                      deleteSFTP(remotePath, filename);
                  
                
              
              else if ((fileEndFormat.length() > 0) && ("".equals(fileFormat))) 
                if (filename.endsWith(fileEndFormat)) 
                  flag = downloadFile(remotePath, filename, localPath, filename);
                  if (flag) 
                    filenames.add(localFileName);
                    if ((flag) && (del))
                      deleteSFTP(remotePath, filename);
                  
                
              
              else 
                flag = downloadFile(remotePath, filename, localPath, filename);
                if (flag) 
                  filenames.add(localFileName);
                  if ((flag) && (del)) 
                    deleteSFTP(remotePath, filename);
                  
                
              
            
          
        
        if (log.isInfoEnabled())
          log.info("download file is success:remotePath=" + remotePath + "and localPath=" + localPath + ",file size is" + v
            .size());
      
      catch (SftpException e) 
        e.printStackTrace();
      
      finally 
      
      return filenames;
    
    return filenames;
  

  public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName)
  
    FileOutputStream fieloutput = null;
    try
    
      File file = new File(localPath + localFileName);

      fieloutput = new FileOutputStream(file);
      this.sftp.get(remotePath + remoteFileName, fieloutput);
      if (log.isInfoEnabled()) 
        log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
      
      int i = 1;
      return i;
     catch (FileNotFoundException e) 
      e.printStackTrace();

      if (null != fieloutput)
        try 
          fieloutput.close();
         catch (IOException e) 
          e.printStackTrace();
        
    
    catch (SftpException e)
    
      e.printStackTrace();

      if (null != fieloutput)
        try 
          fieloutput.close();
         catch (IOException e) 
          e.printStackTrace();
        
    
    finally
    
      if (null != fieloutput) 
        try 
          fieloutput.close();
         catch (IOException e) 
          e.printStackTrace();
        
      
    
    return false;
  

  public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName)
  
    FileInputStream in = null;
    try 
      createDir(remotePath);
      File file = new File(localPath + localFileName);
      in = new FileInputStream(file);

      this.sftp.put(in, remoteFileName);
      int i = 1;
      return i;
     catch (FileNotFoundException e) 
      e.printStackTrace();
     catch (SftpException e) 
      e.printStackTrace();
     finally 
      if (in != null) 
        try 
          in.close();
         catch (IOException e) 
          e.printStackTrace();
        
      
    
    return false;
  

  public boolean bacthUploadFile(String remotePath, String localPath, String backupPath, boolean del)
  
    if (connect()) 
      File file = new File(localPath);
      File[] files = file.listFiles();
      for (int i = 0; i < files.length; i++) 
        File f = files[i];
        if ((f.isFile()) && (f.getName().indexOf("bak") == -1)) 
          String fileName = f.getName();
          uploadFile(remotePath, fileName, localPath, fileName);

          FileUtil.copyBackFile(f, fileName, backupPath);
          if (del) 
            f.delete();
          
        
      

      disconnect();
      return true;
    
    return true;
  

  public boolean deleteFile(String filePath)
  
    File file = new File(filePath);
    if (!file.exists()) 
      return false;
    
    if (!file.isFile()) 
      return false;
    
    return file.delete();
  

  public boolean createDir(String createpath)
  
    try
    
      if (isDirExist(createpath)) 
        this.sftp.cd(createpath);
        return true;
      
      String[] pathArry = createpath.split("/");
      StringBuffer filePath = new StringBuffer("/");
      for (String path : pathArry) 
        if (path.equals("")) 
          continue;
        
        filePath.append(path + "/");
        if (isDirExist(filePath.toString())) 
          this.sftp.cd(filePath.toString());
        
        else 
          this.sftp.mkdir(filePath.toString());

          this.sftp.cd(filePath.toString());
        
      

      this.sftp.cd(createpath);
      return true;
     catch (SftpException e) 
      e.printStackTrace();
    
    return false;
  

  public boolean isDirExist(String directory)
  
    boolean isDirExistFlag = false;
    try 
      SftpATTRS sftpATTRS = this.sftp.lstat(directory);
      isDirExistFlag = true;
      return sftpATTRS.isDir();
     catch (Exception e) 
      if (e.getMessage().toLowerCase().equals("no such file")) 
        isDirExistFlag = false;
      
    
    return isDirExistFlag;
  

  public void deleteSFTP(String directory, String deleteFile)
  
    try
    
      this.sftp.rm(directory + deleteFile);
      if (log.isInfoEnabled())
        log.info("delete file success from sftp.");
    
    catch (SftpException e) 
      e.printStackTrace();
    
  

  public void mkdirs(String path)
  
    File f = new File(path);

    String fs = f.getParent();

    f = new File(fs);

    if (!f.exists())
      f.mkdirs();
  

  public Vector<?> listFiles(String directory)
    throws SftpException
  
    return this.sftp.ls(directory);
  

  public String getHost() 
    return this.host;
  

  public void setHost(String host) 
    this.host = host;
  

  public String getUsername() 
    return this.username;
  

  public void setUsername(String username) 
    this.username = username;
  

  public String getPassword() 
    return this.password;
  

  public void setPassword(String password) 
    this.password = password;
  

  public int getPort() 
    return this.port;
  

  public void setPort(int port) 
    this.port = port;
  

  public ChannelSftp getSftp() 
    return this.sftp;
  

  public void setSftp(ChannelSftp sftp) 
    this.sftp = sftp;
  

 

以上是关于sftp批量上传及批量下载等最全功能的工具类SFTPUtils的主要内容,如果未能解决你的问题,请参考以下文章

paramiko批量上传下载sftp,解决访问windows系列sftp乱码问题

Java实现SFTP上传下载文件及遇到的问题

批量下载的实现及java.lang.IllegalStateException异常

批量ftp上传工具,推荐3款免费的ftp服务器软件,批量ftp上传工具

张明贵-Linux文件上传下载及sCRT配置批量管理功能

示例 SFTP 批量上传脚本,用于 AS400 服务器上传到 Unix SFTP 服务器