zoukankan      html  css  js  c++  java
  • 文件压缩跟解压(本地&Linux服务器)

    远程解压需要的jar包:

    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>ch.ethz.ganymed</groupId>
        <artifactId>ganymed-ssh2</artifactId>
        <version>build210</version>
    </dependency>

    Java实现文件压缩跟解压:

    package com.sunsheen.jfids.studio.monitor.utils;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipOutputStream;
    
    import org.eclipse.core.runtime.Assert;
    
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.Session;
    import ch.ethz.ssh2.StreamGobbler;
    
    import com.sunsheen.jfids.studio.monitor.HKMoniter;
    import com.sunsheen.jfids.studio.monitor.HKMoniterFactory;
    import com.sunsheen.jfids.studio.monitor.common.LogInfo;
    /**
     * 多文件的打包压缩跟解压
     * @author WangSong
     *
     */
    public class ZipFiles {
        private static HKMoniter moniter = HKMoniterFactory.getLogger(ZipFiles.class.getName());
    
         /**
           * 功能:压缩多个文件成一个zip文件(本地)
           * @param srcfile:源文件列表
           * @param zipfile:压缩后的文件
           */
          public static void zipFiles(File[] srcfile,File zipfile){
              if(srcfile.length == 0 || null==srcfile)
                  return;
              
              byte[] buf=new byte[1024];
              try {
                  //ZipOutputStream :完成文件或文件夹的压缩
                  ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
                  for(int i=0;i<srcfile.length;i++){
                      FileInputStream in = new FileInputStream(srcfile[i]);//读取文件
                      out.putNextEntry(new ZipEntry(srcfile[i].getName()));//设置内文件名
                      //写入数据
                      int length;
                      while((length = in.read(buf)) > 0){
                              out.write(buf,0,length);
                      }
                      out.closeEntry();
                      in.close();
                      }
                      out.close();
                    moniter.info("文件【"+zipfile.getName()+"】,压缩完成!");
                      System.out.println("压缩完成.");
                } catch (Exception e) {
                    e.printStackTrace();
                }
              }
          
          /**
           * 功能:解压缩(本地)
           * @param zipfile:需要解压缩的文件
           * @param descDir:解压后的目标目录
           */
          public static void unZipFiles(File zipfile,String descDir){
         
              try {
                  ZipFile zf = new ZipFile(zipfile);//格式化
                  //循环遍历出压缩的每个文件
                  for(Enumeration entries = zf.entries();entries.hasMoreElements();){
                      ZipEntry entry = (ZipEntry) entries.nextElement();
                      String zipEntryName = entry.getName();//当前压缩文件中文件名
                      InputStream in = zf.getInputStream(entry);
                      
                      File mkFile = new File(descDir + zipEntryName);
                      mkFile.createNewFile();
                      
                      OutputStream out=new FileOutputStream(descDir + zipEntryName);
                      byte[] buf1 = new byte[1024];
                      int len;
                      while((len=in.read(buf1)) > 0){
                          out.write(buf1,0,len);
                      }
                      in.close();
                      out.close();
                      moniter.info("文件【"+zipfile.getName()+"】,解压缩完成!");
                      System.out.println("解压缩完成.");
                  }
                } catch (Exception e) {
                    e.printStackTrace();
                }
          }
          
          /**
           * 壓縮指定文件夾下所有文件
           * @param targetZipFile    压缩后的文件     eg:d://logs//log.zip
           * @param logParentFolder    日志文件所在的文件夹    eg:e://logs
           * @return
           */
          public static File zipLogs(String targetZipFile,String logParentFolder){
            //定义日志压缩文件
            File[] logsFileArr = new File(logParentFolder).listFiles();//所有的日志文件
            //創建一個空的目標zip文件
            File resultZip = new File(targetZipFile);
            //壓縮
            zipFiles(logsFileArr, resultZip);
            return resultZip;
          }
          
          
          /**
           * 解压文件(远程)
           * @param romoteAddr    服务器地址
           * @param username    服务器用户名
           * @param password    服务器密码
           * @param targetFolder    服务器上需要解压文件的目录    eg:/usr/local/hk-logs
           * @param zipFileName    需要解压文件的文件名    eg:logs.zip
           */
          public static void remoteUnZip(String romoteAddr,String username,String password,
                  String targetFolder,String zipFileName){
              
              try {
                  Connection connection = new Connection(romoteAddr);// 创建一个连接实例
                  connection.connect();// Now connect
                  boolean isAuthenticated = connection.authenticateWithPassword(username, password);//認證
                  Assert.isTrue(isAuthenticated, "用戶名或者密碼錯誤!");
                  Session sess = connection.openSession();// 創建一個會話
                  sess.requestPTY("bash");
                  sess.startShell();
                  InputStream stdout = new StreamGobbler(sess.getStdout());
                  InputStream stderr = new StreamGobbler(sess.getStderr());
                  BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
                  BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
                  //向服务器上输入命令
                  PrintWriter out = new PrintWriter(sess.getStdin());
                  out.println("cd " + targetFolder);//進入日志文件存放的目录
                  out.println("ll");
                  out.println("unzip -o -d "+targetFolder+" "+zipFileName);//解压文件到指定位置
                  out.println("ll");
                  out.println("exit");
                  out.close();
                  sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,30000);
                  
                  //本机查看远程操作的指令及状态
                  showRemoteShell(stdoutReader,stderrReader,sess);
                  
                  //关闭连接
                  sess.close();
                  connection.close();
              } catch (IOException e) {
                  moniter.error("远程解压文件【"+ zipFileName +"】,错误:" + e);
                  e.printStackTrace(System.err);
                  System.exit(2);
              }
          }
          
          //打印远程指令及状态
          private static void showRemoteShell(BufferedReader stdoutReader,BufferedReader stderrReader,
                  Session sess) throws IOException{
              System.out.println("输入在服务器的指令:");
              while (true) {
                  String line = stdoutReader.readLine();
                  if (line == null)
                      break;
                  System.out.println(line);
              }
              System.out.println("输入指令后对应的显示信息:");
              while (true) {
                  String line = stderrReader.readLine();
                  if (line == null)
                      break;
                  System.out.println(line);
              }
              System.out.println("ExitCode: " + sess.getExitStatus());
          }
          
    }
    View Code
  • 相关阅读:
    e621. Activating a Keystroke When Any Child Component Has Focus
    e587. Filling Basic Shapes
    e591. Drawing Simple Text
    e595. Drawing an Image
    e586. Drawing Simple Shapes
    e636. Listening to All Key Events Before Delivery to Focused Component
    在 PL/SQL 块的哪部分可以对初始变量赋予新值? (选择1项)
    Oracle数据库中,在SQL语句中连接字符串的方法是哪个?(选择1项)
    你判断下面语句,有什么作用?(单选)
    Oracle数据库表空间与数据文件的关系描述正确的是( )
  • 原文地址:https://www.cnblogs.com/Soy-technology/p/11646778.html
Copyright © 2011-2022 走看看