Explain Codes LogoExplain Codes Logo

What is a good Java library to zip/unzip files?

java
zip4j
file-compression
error-handling
Alex KataevbyAlex Kataev·Aug 6, 2024
TLDR

Zipping files in Java is a breeze with Apache Commons Compress, which uses ZipArchiveOutputStream for zipping:

import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; // ... // Step 1: Summon ZipArchiveOutputStream, the Noble Knight of Zipping ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(zipFileName)); // Step 2: Slay the dragon ("compress" the file, so to speak) zos.putArchiveEntry(new ZipArchiveEntry(file.getName())); zos.write(Files.readAllBytes(file.toPath())); zos.closeArchiveEntry(); // Step 3: Celebrate victory (close and release resources, like a responsable knight) zos.close();

Unzipping is effortless with the ZipFile class:

import org.apache.commons.compress.archivers.zip.ZipFile; // ... // Meet ZipFile, your trusty sidekick in the epic quest of unzipping ZipFile zipFile = new ZipFile(zipFilePath); zipFile.stream().forEach(entry -> { Files.copy(zipFile.getInputStream(entry), Paths.get(destDir, entry.getName())); });

These snippets of code assist you in both compressing and extracting files with little to no headache.

Compression libraries you should know

Reliable Comrade: Zip4j

When you require an advanced set of features such as password protection and metadata preservation, Zip4j steps to the plate. Offering a comparable performance to Unix command line tools, it showcases an exemplary API design that is both simple and efficient. Moreover, Zip4j's AES encryption for password protection makes it an ideal choice.

Here’s how you pull Zip4j into your Maven project:

<dependency> <groupId>net.lingala.zip4j</groupId> <artifactId>zip4j</artifactId> <version>1.3.2</version> </dependency>

Utility Classes: Apache Commons-IO's IOUtils

Utility classes can streamline data streaming into and out of your zip files, perks of leveraging something like IOUtils from Apache Commons-IO. For instance, by utilizing IOUtils.copy, you can simplify the procedure of adding and extracting files to and from ZipOutputStream.

Dependency-Free Compressing: java.util.zip

If you want to stick to the basics and shy away from third-party libraries, you can't go wrong with java.util.zip. While it may not provide the same features or user-friendly API as other options, it will get your job done without any external dependencies.

Version-Specific Libraries

If you're working on a project based on Java 11 or beyond, you must ensure your chosen library is optimized for these newer versions. Outdated libraries may not fully utilize the features available in modern Java.

Error Management

Error handling is crucial when it comes to file compression. Build in suitable fallbacks using try-with-resources or catch exceptions to handle unexpected scenarios gracefully.

How about some real Zip4j?

A Zip in the Bud 👶

Creating a new zip file is a cinch with the one-liner provided by Zip4j:

// Say hello to your soon-to-be zip file! new ZipFile("myFiles.zip").addFolder(new File("/myFolder"));

Opening Up

For archives with complex folder structures or sensitive contents, Zip4j's extractAll method is your best bet:

// Knock, Knock! Who's there? It's Zip4j, your friendly neighbourhood extractor! ZipFile zipFile = new ZipFile("mySecureFiles.zip", "password".toCharArray()); if (zipFile.isEncrypted()) { zipFile.extractAll("/myDestFolder"); }

Keepin' it Clean

Use Zip4j's handy utility methods like testZipFile and removeFile to keep your zip files both tidy and in check:

// Cleaning Time! Scrub-a-dub-dub 🛁 zipFile.testZipFile(); zipFile.removeFile(zipFile.getFileHeader("document.txt"));