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

 更新时间:2020年07月28日 15:41:15   作者:张志勇-  
这篇文章主要介绍了如何基于java实现解压ZIP TAR等文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

  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");

  }

}

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

相关文章

  • Java为什么匿名内部类参数引用需要用final进行修饰?

    Java为什么匿名内部类参数引用需要用final进行修饰?

    今天小编就为大家分享一篇关于Java为什么匿名内部类参数引用需要用final进行修饰?,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04
  • spring mvc中的@ModelAttribute注解示例介绍

    spring mvc中的@ModelAttribute注解示例介绍

    在Spring mvc中,注解@ModelAttribute是一个非常常用的注解,下面这篇文章主要给大家介绍了关于spring mvc中@ModelAttribute注解的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。
    2017-09-09
  • Java MD5消息摘要算法原理及实现代码

    Java MD5消息摘要算法原理及实现代码

    这篇文章主要介绍了Java MD5消息摘要算法原理及实现代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • Spring主配置文件(applicationContext.xml) 导入约束详解

    Spring主配置文件(applicationContext.xml) 导入约束详解

    在本篇文章里我们给各位整理的是关于Spring主配置文件(applicationContext.xml) 导入约束的相关知识点内容,需要参考下。
    2019-08-08
  • 云计算实验:Java MapReduce编程

    云计算实验:Java MapReduce编程

    这篇文章主要介绍了云计算实验:Java MapReduce编程, 居于Java围绕MapReduce编程展开详细内容,文章助大家掌握MapReduce编程,理解MapReduce原理,需要的朋友可以参考一下
    2021-12-12
  • 详细解读Druid数据库连接池的使用

    详细解读Druid数据库连接池的使用

    这篇文章主要介绍了Druid数据库连接池的使用,数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个,需要的朋友可以参考下
    2023-03-03
  • Apache Commons Config管理配置文件核心功能使用

    Apache Commons Config管理配置文件核心功能使用

    这篇文章主要为大家介绍了Apache Commons Config管理和使用配置文件核心深入探索,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • Java GUI编程之贪吃蛇游戏简单实现方法【附demo源码下载】

    Java GUI编程之贪吃蛇游戏简单实现方法【附demo源码下载】

    这篇文章主要介绍了Java GUI编程之贪吃蛇游戏简单实现方法,详细分析了贪吃蛇游戏的具体实现步骤与相关注意事项,并附带demo源码供读者下载参考,需要的朋友可以参考下
    2017-09-09
  • spring aop实现用户权限管理的示例

    spring aop实现用户权限管理的示例

    本篇文章主要介绍了spring aop实现用户权限管理的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • Java中的对象流总结(必看篇)

    Java中的对象流总结(必看篇)

    下面小编就为大家带来一篇Java中的对象流总结(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-04-04

最新评论