CompressUtil

Introduction

Although Hutool provides ZipUtil based on JDK for compressing or decompressing ZIP-related files, it still cannot handle compression formats such as 7zip and tar. Therefore, CompressUtil is further encapsulated based on commons-compress.

The supported formats of this tool are:

For streaming compression:

  • GZIP
  • BZIP2
  • XZ
  • XZ
  • PACK200
  • SNAPPY_FRAMED
  • LZ4_BLOCK
  • LZ4_FRAMED
  • ZSTANDARD
  • DEFLATE

For archive files:

  • AR
  • CPIO
  • JAR
  • TAR
  • ZIP
  • 7z

For archive files, Hutool provides two common interfaces:

  • Archiver: Data archiving, providing packaging work such as adding files to the compressed package.
  • Extractor: Unpacking archived data, used for decompressing or extracting compressed files.

Usage

First, introduce commons-compress:

<dependency>
 <groupId>org.apache.commons</groupId>
 <artifactId>commons-compress</artifactId>
 <version>1.21</version>
</dependency>

Compressing files

Let’s take 7Zip as an example:

final File file = FileUtil.file("d:/test/compress/test.7z");
CompressUtil.createArchiver(CharsetUtil.CHARSET_UTF_8, ArchiveStreamFactory.SEVEN_Z, file)
 .add(FileUtil.file("d:/test/someFiles"));
 .finish()
 .close();

In the above code, ArchiveStreamFactory.SEVEN_Z is the custom compression format, which can be selected according to your needs. The add method supports both files and directories. To add multiple files or directories, simply call the add method multiple times. Sometimes, we may not want to add all the files in a directory to the compressed package. In this case, we can use the second parameter Filter of the add method. This interface is used to filter out files that do not need to be added. Here’s an example:

CompressUtil.createArchiver(CharsetUtil.CHARSET_UTF_8, ArchiveStreamFactory.SEVEN_Z, zipFile)
 .add(FileUtil.file("d:/Java/apache-maven-3.6.3"), (file)->{
 if("invalid".equals(file.getName())){
 return false;
 }
 return true;
 })
 .finish().close();

Decompressing files

Let’s take 7Zip as an example:

Extractor extractor = CompressUtil.createExtractor(CharsetUtil.defaultCharset(), FileUtil.file("d:/test/compress/test.7z"));
 extractor.extract(FileUtil.file("d:/test/compress/test2/"));