Working with ZIP Archives in Java: A Complete Guide
In modern Java development, there is often a need to package and unpack files. ZIP is one of the most popular compression formats, supported by the standard Java library. The built-in package java.util.zip provides all the necessary tools for working with ZIP archives without installing third-party dependencies.
Main Classes of the java.util.zip Package
The java.util.zip package includes several key classes for working with archives:
- ZipOutputStream — for creating ZIP archives and writing files to them
- ZipInputStream — for reading the contents of ZIP archives
- ZipEntry — represents an individual entry (file or directory) inside the archive
- ZipFile — for direct access to archive entries by name
- Deflater/Inflater — low-level classes for compressing/decompressing data
Creating a ZIP Archive
To create an archive, ZipOutputStream is used. Each added file is represented as a ZipEntry. Consider an example that packages several files into a single archive:
import java.io.*;import java.util.zip.*;
public class CreateZipExample { public static void main(String[] args) { // Array of files to archive String[] sourceFiles = {"file1.txt", "file2.txt", "image.png"}; String zipFileName = "archive.zip";
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFileName))) { byte[] buffer = new byte[1024];
for (String filePath : sourceFiles) { File file = new File(filePath); // Create an entry in the archive ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry);
// Read the file and write to the archive try (FileInputStream fis = new FileInputStream(file)) { int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } } zos.closeEntry(); } System.out.println("Archive created: " + zipFileName); } catch (IOException e) { e.printStackTrace(); } }}Extracting a ZIP Archive
To read an archive, ZipInputStream is used. The getNextEntry() method sequentially returns all entries in the archive:
import java.io.*;import java.util.zip.*;
public class ExtractZipExample { public static void main(String[] args) { String zipFileName = "archive.zip"; String outputDir = "extracted_files";
new File(outputDir).mkdir();
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName))) { 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 directories if necessary new File(newFile.getParent()).mkdirs();
try (FileOutputStream fos = new FileOutputStream(newFile)) { int length; while ((length = zis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } zis.closeEntry(); System.out.println("Extracted: " + fileName); } } catch (IOException e) { e.printStackTrace(); } }}