ZipUtil

Background

In Java, packaging and compressing files and folders can be quite cumbersome, and often we turn to tools like Zip4j for such operations. However, often times, the zip utility provided in the JDK itself suffices for most of our needs. ZipUtil is a wrapper class specifically designed to simplify the process of compression and decompression using the java.util.zip utility, handling file and directory issues automatically, reducing the complexity involved in such operations significantly.

Methods

Zipping

ZipUtil.zip method provides a series of overloaded methods to meet different zipping requirements, including:

  • Zipping to the current directory (which can handle both files and directories based on their paths)
// Compresses the files/folders in the 'aaa' directory and places the compressed file in 'd:/aaa.zip'
ZipUtil.zip("d:/aaa");
  • Specifying the destination path for the compressed file, with the option of automatically determining if the input is a file or directory
// Compresses the files/folders in the 'aaa' directory and places the compressed file in 'd:/bbb/aaa.zip'
ZipUtil.zip("d:/aaa", "d:/bbb/aaa.zip");

// Compresses the files/folders in the 'aaa' directory and places the compressed file in 'd:/bbb/ccc.zip'
ZipUtil.zip("d:/aaa", "d:/bbb/ccc.zip");
  • Having the option of including the directory structure within the compressed file. For instance, when compressing a directory containing photos, some people might want the compressed file to contain a nested directory structure, while others might want the photos to be at the root of the compressed file. The zip method adds a boolean parameter to support both modes.
// Compresses the 'aaa' directory (and its sub-directories) and places the compressed file in 'd:/bbb/ccc.zip'
ZipUtil.zip("d:/aaa", "d:/bbb/ccc.zip", true);
  • Support for multiple files/directories to be compressed together.
ZipUtil.zip(FileUtil.file("d:/bbb/ccc.zip"), false, 
    FileUtil.file("d:/test1/file1.txt"),
    FileUtil.file("d:/test1/file2.txt"),
    FileUtil.file("d:/test2/file1.txt"),
    FileUtil.file("d:/test2/file2.txt")
);

Unzipping

ZipUtil.unzip is used for decompression. It also provides several overloaded methods to meet different requirements.

// Decompresses 'E:\\aaa\\test.zip' to 'e:\\aaa' directory and returns the decompressed directory
File unzip = ZipUtil.unzip("E:\\aaa\\test.zip", "e:\\aaa");

Gzip Compression and Decompression

Hutool also provides tools for gzip compression and decompression using ZipUtil.gzip and ZipUtil.unGzip.

Zlib Compression and Decompression

ZipUtil.zlib is used for zlib compression and ZipUtil.unZlib is used for zlib decompression.

Note: By default, ZipUtil uses the system encoding when performing operations (generally speaking, Windows uses GBK encoding while Linux uses UTF-8 encoding). When running in an IDE like Eclipse, it will read the encoding based on the current project settings (typically UTF-8).