Working with ZIP Archives in Java: A Complete Guide to java.util.zip
Data archiving is one of the basic tasks in software development. Java provides a powerful and flexible toolkit for working with ZIP archives "out of the box" — the java.util.zip package. In this article, we will thoroughly examine how to create, extract, and modify ZIP archives using standard Java tools.
Main classes of the java.util.zip package
The java.util.zip package contains key classes for working with archives:
- ZipOutputStream — for creating ZIP archives (writing files to an archive)
- ZipInputStream — for reading and extracting ZIP archives
- ZipEntry — represents a single entry (file/directory) inside an archive
- ZipFile — for direct access to archive contents without full extraction
- CheckedOutputStream / CheckedInputStream — for data integrity verification (CRC32, Adler32)
Creating a ZIP archive (ZipOutputStream)
To create an archive, ZipOutputStream is used, which wraps a regular FileOutputStream. Each added file is represented by a ZipEntry object.
import java.io.*;import java.util.zip.*;
public class CreateZip { public static void main(String[] args) throws IOException { String[] sourceFiles = {"file1.txt", "file2.txt", "image.png"}; String zipName = "archive.zip";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName))) { byte[] buffer = new byte[1024];
for (String filePath : sourceFiles) { File file = new File(filePath); FileInputStream fis = new FileInputStream(file);
// Create an entry in the archive ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry);
// Write the file contents int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); System.out.println("Added: " + file.getName()); } } System.out.println("Archive created: " + zipName); }}Important nuances when creating an archive:
- Always call
putNextEntry()before writing data andcloseEntry()after - To add an empty directory, use
ZipEntry(name + "/")— the name must end with "/" - Use try-with-resources for automatic stream closing
Extracting a ZIP archive (ZipInputStream)
To extract files from an archive, ZipInputStream is used. Reading occurs sequentially — entry by entry.
import java.io.*;import java.util.zip.*;
public class ExtractZip { public static void main(String[] args) throws IOException { String zipFile = "archive.zip"; String outputDir = "extracted";
File dir = new File(outputDir); if (!dir.exists()) dir.mkdirs();
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) { ZipEntry entry; byte[] buffer = new byte[1024];
while ((entry = zis.getNextEntry()) != null) { String fileName = entry.getName(); File newFile = new File(outputDir + File.separator + fileName);
// Create parent directories new File(newFile.getParent()).mkdirs();
// Write the file FileOutputStream fos = new FileOutputStream(newFile); int length;