ZIP and GZIP compression in Java

java.util.zip writes and reads ZIP archives, which hold many files, and GZIP streams, which compress a single stream of bytes. Both use the DEFLATE algorithm, which shrinks text and logs dramatically and does nothing for data that is already compressed. This page explains the formats, runs every API, measures the compression levels, and shows the two attacks every extractor must defend against: zip slip and zip bombs.

Contents

How ZIP and GZIP work

Both formats compress with DEFLATE, which combines two ideas. LZ77 replaces a repeated sequence of bytes with a short back-reference ("the 20 bytes that appeared 300 bytes ago"), and Huffman coding gives frequent symbols shorter bit codes. Text, logs, JSON and source code repeat themselves a lot and often shrink by 80 to 99%. Random data, and data that is already compressed, such as JPEG, MP4 or another ZIP, has no repetition to find and gets slightly larger.

The two file formats wrap DEFLATE differently:

  • GZIP holds one compressed stream: a 10-byte header that starts with 1f 8b, the DEFLATE data, and an 8-byte trailer with a CRC-32 checksum and the original size. It has no idea of files or directories, which is why .tar.gz puts a tar archive inside.
  • ZIP holds many entries. Each entry has a local header with its name, followed by its data, compressed with DEFLATE or stored as it is. At the end of the file a central directory lists every entry and where it starts. A reader that can seek reads the directory first; a reader that cannot seek walks the local headers from the start.
The java.util.zip classes and related APIs
APISinceBest for
ZipOutputStreamJava 1.1Creating an archive in one pass
ZipFileJava 1.1Listing and reading entries of an archive on disk, in any order
ZipInputStreamJava 1.1Reading entries in order from any stream, such as a download
GZIPOutputStream, GZIPInputStreamJava 1.1Compressing one stream: files, logs, HTTP bodies
Deflater, InflaterJava 1.1Raw DEFLATE with a chosen level, for your own formats
CRC32, CRC32CJava 1.1, Java 9Checksums
ZIP64 and UTF-8 entry names by defaultJava 7Archives over 4 GB or 65,535 entries; non-ASCII names
ZIP file system (FileSystems.newFileSystem)Java 7Using the Files API inside an archive; updating it

A JAR file is a ZIP file with a META-INF/MANIFEST.MF entry, so everything here applies to JARs too. All programs below were compiled and run on JDK 21 and work on in-memory or temporary files.

Creating and reading a ZIP archive

The program puts three entries into an archive: a directory entry, a repetitive 300,000-byte log, and 100,000 random bytes. The two files were chosen as opposite extremes for compression. It then reads the archive back two ways.

Java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipArchives {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("zip-demo");
        Path zip = dir.resolve("bundle.zip");

        byte[] text = "INFO request handled in 12 ms\n".repeat(10000)
                .getBytes(StandardCharsets.UTF_8);
        byte[] random = new byte[100000];
        new Random(42).nextBytes(random);

        // Writing: one putNextEntry per file, then the bytes, then closeEntry
        try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
            out.putNextEntry(new ZipEntry("logs/"));             // a directory entry
            out.closeEntry();
            out.putNextEntry(new ZipEntry("logs/app.log"));
            out.write(text);
            out.closeEntry();
            out.putNextEntry(new ZipEntry("data/random.bin"));
            out.write(random);
            out.closeEntry();
        }
        System.out.println("zip file size: " + Files.size(zip) + " bytes");

        // ZipFile: random access through the central directory at the end of the archive
        try (ZipFile zf = new ZipFile(zip.toFile())) {
            zf.stream().forEach(e -> System.out.printf("  %-16s %7d -> %7d bytes%s%n",
                    e.getName(), e.getSize(), e.getCompressedSize(),
                    e.isDirectory() ? " (directory)" : ""));
            try (InputStream in = zf.getInputStream(zf.getEntry("logs/app.log"))) {
                System.out.println("first line of logs/app.log: "
                        + new String(in.readNBytes(29), StandardCharsets.UTF_8));
            }
        }

        // ZipInputStream: reads entries in order from any stream, e.g. a download
        int entries = 0;
        try (ZipInputStream in = new ZipInputStream(Files.newInputStream(zip))) {
            for (ZipEntry e; (e = in.getNextEntry()) != null; ) {
                entries++;
                in.transferTo(OutputStream.nullOutputStream());
            }
        }
        System.out.println("entries read by ZipInputStream: " + entries);

        Files.delete(zip);
        Files.delete(dir);
    }
}

Output:

Output
zip file size: 101179 bytes
  logs/                  0 ->       2 bytes (directory)
  logs/app.log      300000 ->     780 bytes
  data/random.bin   100000 ->  100035 bytes
first line of logs/app.log: INFO request handled in 12 ms
entries read by ZipInputStream: 3
  • The log shrank from 300,000 to 780 bytes, because it is the same 30-byte line 10,000 times. The random data got slightly larger, 100,035 bytes: DEFLATE found nothing to remove and added its own block structure.
  • Entry names use / as the separator on every platform, and a name ending in / is a directory entry.
  • ZipFile read the central directory, so it listed all entries with their sizes and opened logs/app.log directly. It needs a file it can seek in.
  • ZipInputStream read the 3 entries in order from a plain InputStream. Each getNextEntry moves to the next entry's data, and reading returns -1 at the end of the current entry. It never sees the central directory, so the sizes in its entries can be unknown (-1) until the entry has been read.

STORED entries, checksums and entry name charsets

An entry does not have to be compressed. STORED keeps the bytes as they are, which saves CPU for data that will not shrink. The program stores a 50,000-byte stand-in for a photo both ways, and then writes an entry name the way older Windows tools did, in the DOS code page 437, to show what happens when the reader assumes UTF-8.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class StoredAndNames {

    public static void main(String[] args) throws IOException {
        byte[] photo = new byte[50000];                    // stands in for a JPEG: no redundancy
        new Random(3).nextBytes(photo);

        // STORED: no compression, but size and CRC-32 must be known up front
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ZipOutputStream out = new ZipOutputStream(bytes)) {
            ZipEntry e = new ZipEntry("photo.jpg");
            e.setMethod(ZipEntry.STORED);
            out.putNextEntry(e);
        } catch (ZipException ex) {
            System.out.println("STORED without size and CRC: ZipException: " + ex.getMessage());
        }

        CRC32 crc = new CRC32();
        crc.update(photo);
        int[] sizes = new int[2];
        for (int method : new int[] {ZipEntry.STORED, ZipEntry.DEFLATED}) {
            ByteArrayOutputStream zip = new ByteArrayOutputStream();
            try (ZipOutputStream out = new ZipOutputStream(zip)) {
                ZipEntry e = new ZipEntry("photo.jpg");
                e.setMethod(method);
                if (method == ZipEntry.STORED) {
                    e.setSize(photo.length);
                    e.setCrc(crc.getValue());
                }
                out.putNextEntry(e);
                out.write(photo);
                out.closeEntry();
            }
            sizes[method == ZipEntry.STORED ? 0 : 1] = zip.size();
        }
        System.out.printf("50,000 random bytes: STORED archive %,d bytes, DEFLATED %,d bytes%n",
                sizes[0], sizes[1]);
        System.out.printf("CRC-32 of the data: %08x%n", crc.getValue());

        // Entry names: UTF-8 by default, but older tools wrote the DOS code page 437
        ByteArrayOutputStream legacy = new ByteArrayOutputStream();
        Charset cp437 = Charset.forName("IBM437");
        try (ZipOutputStream out = new ZipOutputStream(legacy, cp437)) {
            out.putNextEntry(new ZipEntry("Übersicht.txt"));
            out.write('x');
            out.closeEntry();
        }
        try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(
                legacy.toByteArray()))) {
            System.out.println("read as UTF-8: " + in.getNextEntry().getName());
        } catch (IllegalArgumentException ex) {
            System.out.println("read as UTF-8: IllegalArgumentException: " + ex.getMessage());
        }
        try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(
                legacy.toByteArray()), cp437)) {
            System.out.println("read as IBM437: " + in.getNextEntry().getName());
        }
        System.out.println("name bytes in UTF-8: "
                + "Übersicht.txt".getBytes(StandardCharsets.UTF_8).length + ", in IBM437: "
                + "Übersicht.txt".getBytes(cp437).length);
    }
}

Output:

Output
STORED without size and CRC: ZipException: STORED entry missing size, compressed size, or crc-32
50,000 random bytes: STORED archive 50,116 bytes, DEFLATED 50,152 bytes
CRC-32 of the data: f5dc5290
read as UTF-8: IllegalArgumentException: malformed input off : 0, length : 1
read as IBM437: Übersicht.txt
name bytes in UTF-8: 14, in IBM437: 13
  • A STORED entry must declare its size and CRC-32 before the data, because the local header is written first and cannot be fixed afterwards in a stream. Without them, putNextEntry threw ZipException. DEFLATED entries write those values after the data instead.
  • For random data, the stored archive was smaller than the deflated one, 50,116 against 50,152 bytes, and it cost no compression time. Archivers store media files for the same reason.
  • Java has written and read entry names as UTF-8 by default since Java 7. The name written in IBM437 made the default UTF-8 reader throw IllegalArgumentException ("malformed input") at the first entry. Passing the right charset to ZipInputStream or ZipFile read "Übersicht.txt" correctly. When you receive archives from unknown tools, catch this exception and retry with IBM437.

Extracting safely: zip slip

An entry name is just a string, and an archive can contain names like ../../outside.txt. Extracting it naively with target.resolve(name) writes outside the target directory, which attackers have used to overwrite configuration and code. This is known as zip slip. The program builds an archive with two normal entries and two hostile ones, then extracts it with a check: each destination is resolved, normalized, and accepted only if it is still inside the target directory.

Java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class SafeExtract {

    // Reject entries whose names would land outside the target directory ("zip slip")
    static void extract(Path zip, Path target) throws IOException {
        Path root = target.toAbsolutePath().normalize();
        try (ZipInputStream in = new ZipInputStream(Files.newInputStream(zip))) {
            for (ZipEntry e; (e = in.getNextEntry()) != null; ) {
                Path dest = root.resolve(e.getName()).normalize();
                if (!dest.startsWith(root)) {
                    System.out.println("  rejected: " + e.getName());
                    continue;
                }
                if (e.isDirectory()) {
                    Files.createDirectories(dest);
                } else {
                    Files.createDirectories(dest.getParent());
                    Files.copy(in, dest, StandardCopyOption.REPLACE_EXISTING);
                    System.out.println("  extracted: " + root.relativize(dest));
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("slip");
        Path zip = dir.resolve("upload.zip");
        try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
            for (String name : new String[] {"docs/readme.txt", "../../outside.txt",
                "docs/../../escape.txt", "img/logo.txt"}) {
                out.putNextEntry(new ZipEntry(name));
                out.write(name.getBytes(StandardCharsets.UTF_8));
                out.closeEntry();
            }
        }
        Path target = Files.createDirectory(dir.resolve("extracted"));
        extract(zip, target);
        try (var files = Files.walk(dir)) {
            System.out.println("files written anywhere: " + files.filter(Files::isRegularFile)
                    .filter(p -> !p.equals(zip)).count());
        }
    }
}

Output:

Output
extracted: docs/readme.txt
  rejected: ../../outside.txt
  rejected: docs/../../escape.txt
  extracted: img/logo.txt
files written anywhere: 2

Both escape attempts were rejected, including docs/../../escape.txt, which starts with a harmless-looking directory. After the extraction, only the 2 legitimate files exist. The check uses Path.startsWith, which compares whole path elements; a string comparison would accept a sibling directory such as extracted-evil. The same check protects any code that builds paths from names it did not choose; see the Path and Files API.

Zip bombs: limiting what an archive may expand to

The second attack is size. Long runs of identical bytes compress about a thousand to one with DEFLATE, so a small upload can expand to fill a disk or the heap, and the sizes recorded in entry headers are written by the attacker. The program builds a 100 MB archive of zeros and extracts it with limits on the number of entries and on the bytes actually decompressed.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class BombGuard {

    static final long MAX_TOTAL = 20000000;               // 20 MB for the whole archive
    static final int MAX_ENTRIES = 1000;

    // Counts real decompressed bytes; the sizes in the entry headers can lie
    static long extract(InputStream source) throws IOException {
        long total = 0;
        int entries = 0;
        byte[] buf = new byte[8192];
        try (ZipInputStream in = new ZipInputStream(source)) {
            for (ZipEntry e; (e = in.getNextEntry()) != null; ) {
                if (++entries > MAX_ENTRIES) {
                    throw new IOException("too many entries");
                }
                int n;
                while ((n = in.read(buf)) != -1) {
                    total += n;
                    if (total > MAX_TOTAL) {
                        throw new IOException(String.format(
                                "stopped after %,d bytes: archive expands past the limit",
                                total));
                    }
                    // a real extractor writes buf[0..n) to the destination here
                }
            }
        }
        return total;
    }

    public static void main(String[] args) throws IOException {
        // 10 entries of 10 MB of zeros each: 100 MB that compresses extremely well
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        byte[] zeros = new byte[1 << 20];
        try (ZipOutputStream out = new ZipOutputStream(bytes)) {
            for (int i = 0; i < 10; i++) {
                out.putNextEntry(new ZipEntry("part" + i + ".bin"));
                for (int mb = 0; mb < 10; mb++) {
                    out.write(zeros);
                }
                out.closeEntry();
            }
        }
        byte[] bomb = bytes.toByteArray();
        System.out.printf("archive: %,d bytes, would expand to %,d bytes (ratio %,d:1)%n",
                bomb.length, 100L << 20, (100L << 20) / bomb.length);
        try {
            extract(new ByteArrayInputStream(bomb));
        } catch (IOException e) {
            System.out.println("guarded extraction: " + e.getMessage());
        }
    }
}

Output:

Output
archive: 103,152 bytes, would expand to 104,857,600 bytes (ratio 1,016:1)
guarded extraction: stopped after 20,004,030 bytes: archive expands past the limit
  • About 100 KB of archive described 100 MB of data, a ratio of about 1,000 to 1. Nested archives, ZIPs inside ZIPs, multiply the ratio further.
  • The guard counted the bytes as they came out of the decompressor and stopped just past the 20 MB limit, after reading only a fifth of the data. Checking ZipEntry.getSize() instead would not be safe, because the attacker writes that value.
  • A real extractor also limits the number of entries, here 1,000, and often the ratio of decompressed to compressed size per entry.

GZIP and compression levels

GZIP compresses one stream, which suits single files, HTTP responses and logs. The program generates a 715,595-byte log with varying user numbers and status codes, closer to real data than the repeated line above. It compresses that log and the same amount of random bytes, compares the DEFLATE levels in size and time, and finally reads the compressed log line by line.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipDemo {

    static byte[] gzip(byte[] data) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (GZIPOutputStream out = new GZIPOutputStream(bytes)) {
            out.write(data);
        }
        return bytes.toByteArray();
    }

    static int deflatedSize(byte[] data, int level) {
        Deflater d = new Deflater(level);
        d.setInput(data);
        d.finish();
        byte[] buf = new byte[data.length + 64];
        int n = d.deflate(buf);
        d.end();
        return n;
    }

    public static void main(String[] args) throws IOException {
        StringBuilder log = new StringBuilder();
        Random r = new Random(7);
        for (int i = 0; i < 20000; i++) {
            log.append("2026-01-15 INFO user=").append(r.nextInt(500)).append(" status=")
                    .append(r.nextBoolean() ? 200 : 404).append('\n');
        }
        byte[] text = log.toString().getBytes(StandardCharsets.UTF_8);
        byte[] noise = new byte[text.length];
        r.nextBytes(noise);

        byte[] gzText = gzip(text);
        byte[] gzNoise = gzip(noise);
        System.out.printf("log text:     %,d -> %,d bytes (%.0f%% smaller)%n", text.length,
                gzText.length, 100.0 * (text.length - gzText.length) / text.length);
        System.out.printf("random bytes: %,d -> %,d bytes (larger than the input)%n",
                noise.length, gzNoise.length);
        System.out.printf("gzip header bytes: %02x %02x%n", gzText[0], gzText[1]);

        // Size and time per level, best of 5 (rough comparison)
        for (int level : new int[] {Deflater.NO_COMPRESSION, Deflater.BEST_SPEED,
            Deflater.DEFAULT_COMPRESSION, Deflater.BEST_COMPRESSION}) {
            long best = Long.MAX_VALUE;
            int size = 0;
            for (int i = 0; i < 6; i++) {
                long start = System.nanoTime();
                size = deflatedSize(text, level);
                if (i > 0) {                                // run 0 is a warm-up
                    best = Math.min(best, System.nanoTime() - start);
                }
            }
            System.out.printf("deflate level %2d: %,9d bytes %6.1f ms%n", level, size,
                    best / 1e6);
        }

        // Read compressed text line by line without unpacking it to a file first
        try (BufferedReader in = new BufferedReader(new InputStreamReader(
                new GZIPInputStream(new ByteArrayInputStream(gzText)), StandardCharsets.UTF_8))) {
            long notFound = in.lines().filter(l -> l.endsWith("404")).count();
            System.out.println("404 lines read from the gzip stream: " + notFound);
        }
    }
}

Output (times are a rough comparison on a 2-CPU Linux VM, JDK 21, best of 5):

Output
log text:     715,595 -> 48,245 bytes (93% smaller)
random bytes: 715,595 -> 715,833 bytes (larger than the input)
gzip header bytes: 1f 8b
deflate level  0:   715,656 bytes    0.3 ms
deflate level  1:    67,214 bytes    1.2 ms
deflate level -1:    48,233 bytes    4.4 ms
deflate level  9:    46,951 bytes    9.2 ms
404 lines read from the gzip stream: 10051
  • The log is 93% smaller; random data again grew slightly.
  • Every GZIP stream starts with the bytes 1f 8b, a quick way to recognize compressed data, as the buffered streams page does with mark and reset.
  • Level 0 only wraps the data. Level 1 was the fastest real compression and gave the largest output; level 9 was several times slower than level 1 for an output only about 30% smaller. The default, -1, which means level 6, was within a few percent of level 9 in size at about half its time. Higher levels rarely pay off.
  • Wrapping GZIPInputStream in a reader processes a compressed log as a stream of lines, without unpacking it to disk first. The same works for large files; see handling large files.

The ZIP file system

The JDK includes a file system provider for ZIP files. FileSystems.newFileSystem(zipPath, env) opens an archive as a FileSystem, and then the ordinary Files methods, such as write, copy, delete and walk, work on its entries. Changes are written to the archive when the file system is closed.

Java
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.stream.Stream;

public class ZipFileSystemDemo {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("zipfs");
        Path zip = dir.resolve("site.zip");

        // Treat a ZIP archive as a file system and use the normal Files API inside it
        try (FileSystem fs = FileSystems.newFileSystem(zip, Map.of("create", "true"))) {
            Path index = fs.getPath("/web/index.html");
            Files.createDirectories(index.getParent());
            Files.writeString(index, "home page");
            Files.writeString(fs.getPath("/web/about.html"), "about us");
            Files.copy(index, fs.getPath("/web/index.bak"));
        }

        // Reopen it, change one entry in place and list the content
        try (FileSystem fs = FileSystems.newFileSystem(zip)) {
            Files.writeString(fs.getPath("/web/about.html"), "about us, updated");
            Files.delete(fs.getPath("/web/index.bak"));
            try (Stream<Path> s = Files.walk(fs.getPath("/"))) {
                s.filter(Files::isRegularFile).sorted().forEach(p -> {
                    try {
                        System.out.println(p + ": " + Files.readString(p));
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        }
        System.out.println("archive size on disk: " + Files.size(zip) + " bytes");
        Files.delete(zip);
        Files.delete(dir);
    }
}

Output:

Output
/web/about.html: about us, updated
/web/index.html: home page
archive size on disk: 454 bytes

The archive was created with "create" = "true", then reopened to update one entry and delete another, which ZipOutputStream cannot do without rewriting the whole archive yourself. The provider does that rewriting on close, so updating one entry in a large archive still costs a full rewrite. The same provider reads JAR files on the classpath; see classpath resources for listing a folder inside a JAR.

Which API to use

Choosing a compression API
NeedUse
Create an archive in one passZipOutputStream
List or read selected entries of a file on diskZipFile
Read an archive from a stream, such as an uploadZipInputStream
Modify an existing archive, or use Files on itZIP file system
Compress a single streamGZIPOutputStream / GZIPInputStream
Already-compressed media in an archiveSTORED entries with size and CRC set
Archives from untrusted sourcesPath check against zip slip, plus limits on entries and decompressed bytes
Archives from old Windows toolsPass Charset.forName("IBM437") when UTF-8 fails
Fast compression of logs or network dataDeflater level 1, or the default level for a better ratio