当前位置: 移动技术网 > IT编程>开发语言>Java > 如何基于java实现解压ZIP TAR等文件

如何基于java实现解压ZIP TAR等文件

2020年07月29日  | 移动技术网IT编程  | 我要评论
java实现对常用.zip , .tar, .tar.bz2, .bz2 ,.tar.gz ,.gz格式文件的解压。  首先需要引入maven依赖,这里使用的是apache的压缩工具包common-c

  java实现对常用.zip , .tar, .tar.bz2, .bz2 ,.tar.gz ,.gz格式文件的解压。

  首先需要引入maven依赖,这里使用的是apache的压缩工具包common-compress,改工具包支持解压、压缩,此代码中我列举出一个zip的压缩示例,其他格式的只需切换改格式对应的流即可。

对于rar格式文件的解压,目前该工具包还不支持,希望大家做过的可以多多交流。

<dependency>
  <groupid>org.apache.commons</groupid>
  <artifactid>commons-compress</artifactid>
  <version>1.19</version></dependency>
import org.apache.commons.compress.archivers.tar.tararchiveentry;
import org.apache.commons.compress.archivers.tar.tararchiveinputstream;
import org.apache.commons.compress.archivers.zip.ziparchiveentry;
import org.apache.commons.compress.archivers.zip.ziparchiveinputstream;
import org.apache.commons.compress.archivers.zip.ziparchiveoutputstream;
import org.apache.commons.compress.compressors.bzip2.bzip2compressorinputstream;
import org.apache.commons.compress.compressors.gzip.gzipcompressorinputstream;
import org.apache.commons.compress.utils.ioutils;
import java.io.*;

/**
 * @author :zhangzhiyong
 * @description:  java实现常见文件格式的解压与压缩
 *         支持.zip .tar .tar.bz2 .bz2 .tar.gz .gz
 *         其他格式compress包也支持,在此基础上开发即可
 *         另外压缩文件只写了zip压缩的方法zipcompression,其他的格式类似,换成对应的文件流即可。
 *   暂不支持rar压缩格式,rar可以用junrar的工具包,但是有缺陷:
 *   其一:如果压缩文件中有中文名字的文件夹,解压以后文件夹名字是乱码,但是不影响文件夹里面的文件;
 *   其二:最新 winrar 压缩产生的 .rar 文件可能会无法解压。
 *   缺陷原因:rar 有版权,有些东西没有公开,对解压有一些限制,即使其他解压包也可能有问题,但是建议尝试。
 * @date :2020/7/1 20:44
 */
public class compressionfileutil {
  /**
   * @param filepath 需要解压的zip文件的完成路径。
   * @param unzippath 解压过后生成文件的存放路径
   * @description: 对zip文件进行解压。
   * @return: boolean
   * @author: zzy
   * @time: 2020/7/2 14:47
   */
  public static boolean zipuncompress(string filepath, string unzippath) throws ioexception {

    system.out.println("开始解压zip..........");
    fileinputstream fis = null;
    ziparchiveinputstream zis = null;
    try {
      file file = new file(filepath);
      fis = new fileinputstream(file);
      zis = new ziparchiveinputstream(fis);
      ziparchiveentry nze = null;
      while ((nze = zis.getnextzipentry()) != null) {
        fileoutputstream os = null;
        bufferedoutputstream bos = null;
        try {
          system.out.println("正在解压....." + nze.getname());
          //自动添加file.separator文件路径的分隔符,根据系统判断是\\还是/
          string dir = unzippath + file.separator + nze.getname(); //解压全路径
          system.out.println("dir---" + dir);
          file file1 = null;
          if (nze.isdirectory()) {
            file1 = new file(dir);
            file1.mkdirs();
          } else {
            file1 = new file(dir);
            os = new fileoutputstream(file1);
            bos = new bufferedoutputstream(os);
             /*byte [] bt = new byte[1024];
             int len = 0;
             while((len = zis.read(bt,0,1024)) != -1){
               bos.write(bt,0,len);
             }*/
            ioutils.copy(zis, bos); //作用与上面注释代码一样
          }
          system.out.println("解压完成......");
        } catch (filenotfoundexception e) {
          e.printstacktrace();
          return false;
        } finally {
          if (bos != null) {
            bos.close();
          }
          if (os != null) {
            os.close();
          }
        }
      }
    } catch (exception e) {
      e.printstacktrace();
      return false;
    } finally {
      if (zis != null) {
        zis.close();
      }
      if (fis != null) {
        fis.close();
      }
    }
    return true;
  }

  /**
   * @param filespatharray 多个文件的绝对路径,是一个数组。
   * @param zipfilepath  生成的压缩文件的位置,包括生成的文件名,如d:\zip\test.zip
   * @description: 将多个文件压缩成zip压缩包。
   * @return: boolean
   * @author: zzy
   * @time: 2020/7/2 14:42
   */
  public static boolean zipcompression(string[] filespatharray, string zipfilepath) throws exception {
    system.out.println("开始压缩zip文件");
    ziparchiveoutputstream zos = null;
    fileoutputstream fos = null;
    try {
      fos = new fileoutputstream(new file(zipfilepath));
      zos = new ziparchiveoutputstream(fos);
      for (string filepath : filespatharray) {
        fileinputstream fis = null;
        bufferedinputstream bis = null;
        try {
          file file = new file(filepath);
          // 第二个参数如果是文件全路径名,那么压缩时也会将路径文件夹也缩进去;
          // 我们只压缩目标文件,而不压缩该文件所处位置的相关文件夹,所以这里我们用file.getname()
          system.out.println("开始压缩..." + file.getname());
          ziparchiveentry zae = new ziparchiveentry(file, file.getname());
          zos.putarchiveentry(zae);
          fis = new fileinputstream(file);
          bis = new bufferedinputstream(fis);
          int count;
          byte[] bt = new byte[1024];
          while ((count = bis.read(bt, 0, 1024)) != -1) {
            zos.write(bt, 0, count);
          }
        } finally {
          zos.closearchiveentry();
          if (bis != null)
            bis.close();
          if (fis != null)
            fis.close();
        }
      }
    } finally {
      if (zos != null)
        zos.close();
      if (fos != null)
        fos.close();
    }
    system.out.println("压缩完成......");
    return true;
  }

  /**
   * @param inputstream 每种tar文件用不同的输入流,uncompress方法中已注明
   * @param untarpath  tar文件解压后的存放路径
   * @description: 解压tar类文件,包括.tar .tar.bz2 .tar.gz
   * @return: void
   * @author: zzy
   * @time: 2020/7/2 17:42
   */
  public static void untar(inputstream inputstream, string untarpath) throws ioexception {

    fileinputstream fis = null;
    tararchiveinputstream tis = null;
    try {
      tis = new tararchiveinputstream(inputstream);
      tararchiveentry nte = null;
      system.out.println("开始解压......");
      while ((nte = tis.getnexttarentry()) != null) {
        string dir = untarpath + file.separator + nte.getname();
        system.out.println("正在解压......" + dir);
        fileoutputstream fos = null;
        bufferedoutputstream bos = null;
        try {
          if (nte.isdirectory()) {
            file file1 = new file(dir);
            file1.mkdirs();
          } else {
            file file2 = new file(dir);
            fos = new fileoutputstream(file2);
            bos = new bufferedoutputstream(fos);
            ioutils.copy(tis, bos);
          }
        } catch (exception e) {
          e.printstacktrace();
        } finally {
          if (bos != null) {
            bos.close();
          }
          if (fos != null) {
            fos.close();
          }
        }
      }
      system.out.println("解压完成......");
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      if (tis != null) {
        tis.close();
      }
      if (fis != null) {
        fis.close();
      }
    }
  }

  public static boolean uncompress(string filepath,string uncompresspath) throws exception {
    string filetype = filepath.touppercase();
    if(filetype.endswith(".tar")){
      system.out.println("解压的.tar包");
      //.tar包用一般的fileinputstream流读取
      untar(new fileinputstream(filepath),uncompresspath);
    }
    else if(filetype.endswith(".tar.gz")){
      system.out.println("解压的.tar.gz包");
      //.tar.gz包要用gzipcompressorinputstream读取
      untar(new gzipcompressorinputstream(new fileinputstream(filepath)),uncompresspath);
    }
    else if(filetype.endswith(".tar.bz2")){
      system.out.println("解压的.tar.bz2包");
      untar(new bzip2compressorinputstream(new fileinputstream(filepath)),uncompresspath);
    }
    else if(filetype.endswith(".zip")){
      system.out.println("解压的.zip包");
      zipuncompress(filepath,uncompresspath);
    }
    else{
      system.out.println("暂不支持该种格式文件的解压");
    }
    return true;
  }

  public static void main(string[] args) throws exception {

    uncompress("d:\\test\\zip\\nginx-1.18.0.rar","d:\\test\\zip");

  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网