使用JSch实现SFTP文件传输

                                连接过程:

   public ChannelSftp connectWithABS(String ip, int port, String username, String password) { 
        logger.info("SFTP 连接" + ip + " " + port + " " + username);
        try { 
            JSch jsch = new JSch();  // 创建JSch对象
            jsch.getSession(username, ip, port);  // 根据用户名,主机ip,端口获取一个Session对象
            Session sshSession = jsch.getSession(username, ip, port); 
            System.out.println("Session created."); 
            sshSession.setPassword(password); 
            Properties sshConfig = new Properties(); 
            sshConfig.put("StrictHostKeyChecking", "no"); 
            sshSession.setConfig(sshConfig);  // 为Session对象设置properties
            sshSession.connect();  // 通过Session建立链接
            System.out.println("Session connected."); 
            System.out.println("Opening Channel."); 
            channel = (ChannelSftp) sshSession.openChannel("sftp");  // 打开SFTP通道
            channel.connect();  // 建立SFTP通道的连接
            sftp = (ChannelSftp) channel;
            System.out.println("Connected to " + ip + ".");
            logger.info("SFTP 登录成功");
   isOpen=true;
        } catch (Exception e) { 
            logger.error("SFTP 连接失败" + e.getMessage());
            isOpen=false;
            e.printStackTrace() ;
        } 
        return sftp; 

                                        连接之后文件的验证下载

public class WZBK_Transfer {
 
    Logger log = Logger.getLogger("sftp file download");

 //static Transfer sftp = null;
 static ChannelSftp sftp;
 public boolean transfer(String date,String[] arr) throws Exception {
  String localHomePath = localPathHead+"/home/"+date;
  String remotePath = remotePathHead;
  File file =new File(localHomePath);
  if(!file.exists()) {
   file.mkdirs();
  }
  //Transfer sftp1 = null;
  log.info("link sftp");
  SFTPUtil sftpUtil=new SFTPUtil();
  sftp=sftpUtil.connectWithABS("IP",22, "用户名", "密码");//连接sftp服务器
        int G4Flag = 0;
        int G4DateNumber = 0;
        FileTsfInfo G4fileTsfInfo = new FileTsfInfo();
        int count=0;
        String data=date;
        Vector<ChannelSftp.LsEntry> lists=sftp.ls("服务器文件路径");
        List<String> l=new ArrayList();

  验证文件名:
        String[] strAr = Source.FILEARR2;
        for(LsEntry list : lists) {
         String ext = list.getFilename().substring(list.getFilename().lastIndexOf(".") + 1);
            System.out.println(ext);
          if(ext.equals("gz")) {
           l.add(list.getFilename()); 
           count++;
          }
       }
        System.out.println(data+" gz文件个数为:"+ count);
   if(count>=28) {
        boolean flag=true;
     for(String str1:strAr) {
           if(!l.contains(str1+"_HNT_"+date+".tar.gz")&&!l.contains(str1+date+".tar.gz")) {
            flag=false;
            break;
           }else if(flag){
            System.out.println("文件名正确");
            for (String str : arr) {
             //该对象记录文件传输详情
             FileTsfInfo fileTsfInfo = new FileTsfInfo();
             fileTsfInfo.setFileName(str+"_HNT_"+date);
             fileTsfInfo.setFileFormat(".tar.gz");
             Date startTime = null;
             Date endTime = null;
              
             try {
              if("rrs".equals(str.subSequence(0, 3))) {
               if(G4Flag==0) {
                fileTsfInfo.setFileName("G4"+date);
                startTime = new Date();

下载的方法:
                sftpUtil.get(fileTsfInfo.getFileName()+".tar.gz", localHomePath,remotePath);
                endTime = new Date();
                log.info("G4"+date+".tar.gz" + " download successful");
                UnzipUtils.unTarGz(localHomePath+"/"+"G4"+date+".tar.gz", localHomePath);//进行文件的压缩输入输出
               }
               G4Flag++;
               
               String [] strArr = UnzipUtils.getFileNameBySuffix(localHomePath+"/"+"G4"+date+"/"+str, ".gz");
               for(String fileName:strArr) {
                UnzipUtils.unGz(localHomePath+"/"+"G4"+date+"/"+str+"/"+fileName+".gz");
               }
               int dataNumber =formatDoc(str,localHomePath+"/"+"G4"+date+"/"+str,localPathHead,strArr);
               G4DateNumber+=dataNumber;
               log.info("Reslove as "+ str + ".csv");
               
               if (startTime!=null){
                G4fileTsfInfo.setFileFormat(".tar.gz");
                G4fileTsfInfo.setFileName("G4"+date);
                G4fileTsfInfo.setFileSize(new File(localHomePath+"/"+"G4"+date+".tar.gz").length()+"kb");
                G4fileTsfInfo.setStartTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(startTime));
                G4fileTsfInfo.setEndTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(endTime));
                G4fileTsfInfo.setTreatTime((endTime.getTime()-startTime.getTime())+"ms");
                G4fileTsfInfo.setTreatStatus("成功");
               }
               
               if(G4Flag == 3) {
                G4fileTsfInfo.setDataNumber(G4DateNumber);
                FileTsfInfoUtil.insert(G4fileTsfInfo);
               }
              }else {
               try {
                startTime = new Date();

下载方法的第二种情况:
                sftpUtil.get(fileTsfInfo.getFileName()+".tar.gz", localHomePath,remotePath);
                endTime = new Date();
                fileTsfInfo.setFileSize(new File(localHomePath+"/"+str+"_HNT_"+date+".tar.gz").length()+"kb");
                log.info(str+"_HNT_"+date+".tar.gz" + " download successful");
                //解压到当前文件夹
                UnzipUtils.unTarGz(localHomePath+"/"+str+"_HNT_"+date+".tar.gz", localHomePath);
                
                String [] strArr = UnzipUtils.getFileNameBySuffix(localHomePath+"/"+str+"_HNT_"+date+"/"+str, ".gz");
                for(String fileName:strArr) {
                 //打开这个文件夹 解压里面的数据到本文件夹
                    UnzipUtils.unGz(localHomePath+"/"+str+"_HNT_"+date+"/"+str+"/"+fileName+".gz");
                }
                
                //解析该文件到mytest文件夹下  
                int dataNumber =formatDoc(str,localHomePath+"/"+str+"_HNT_"+date+"/"+str,localPathHead,strArr);
                fileTsfInfo.setDataNumber(dataNumber);
                log.info("Reslove as "+ str + ".csv");
                
                fileTsfInfo.setStartTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(startTime));
                fileTsfInfo.setEndTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(endTime));
                fileTsfInfo.setTreatTime((endTime.getTime()-startTime.getTime())+"ms");
                fileTsfInfo.setTreatStatus("成功");
                FileTsfInfoUtil.insert(fileTsfInfo);
               }catch(Exception e) {
                continue;
               }
               
              }
                      
             } catch (Exception e) {
              sftpUtil.close();
              e.printStackTrace();
              return false;
             }
            
            }
            sftpUtil.close();
            return true;
           }
         }
     sftpUtil.close();
     return true;
   }else {
    System.out.println("文件个数不对");
    sftpUtil.close();
    return false;
   }
      
}

posted @ 2019-01-10 11:39  SevenChilde  阅读(1860)  评论(0编辑  收藏  举报