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
, 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 why1f 8b puts a tar archive inside..tar.gz - 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.
| API | Since | Best for |
|---|---|---|
ZipOutputStream | Java 1.1 | Creating an archive in one pass |
ZipFile | Java 1.1 | Listing and reading entries of an archive on disk, in any order |
ZipInputStream | Java 1.1 | Reading entries in order from any stream, such as a download |
GZIPOutputStreamGZIPInputStream | Java 1.1 | Compressing one stream: files, logs, HTTP bodies |
DeflaterInflater | Java 1.1 | Raw DEFLATE with a chosen level, for your own formats |
CRC32CRC32C | Java 1.1, Java 9 | Checksums |
| ZIP64 and UTF-8 entry names by default | Java 7 | Archives over 4 GB or 65,535 entries; non-ASCII names |
ZIP file system (FileSystems.newFileSystem | Java 7 | Using the Files |
A JAR file is a ZIP file with a META-INF/MANIFEST.MF
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.
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:
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./ read the central directory, so it listed all entries with their sizes and openedZipFile directly. It needs a file it can seek in.logs/app.log read the 3 entries in order from a plainZipInputStream . EachInputStream 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.getNextEntry
STORED entries, checksums and entry name charsets
An entry does not have to be compressed. STORED
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:
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
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,STORED threwputNextEntry .ZipException entries write those values after the data instead.DEFLATED - 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
("malformed input") at the first entry. Passing the right charset toIllegalArgumentException orZipInputStream read "Übersicht.txt" correctly. When you receive archives from unknown tools, catch this exception and retry with IBM437.ZipFile
Extracting safely: zip slip
An entry name is just a string, and an archive can contain names like ../../outside.txttarget.resolve(name)
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:
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.txtPath.startsWithextracted-evil
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.
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:
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
instead would not be safe, because the attacker writes that value.ZipEntry.getSize() - 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.
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):
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
, a quick way to recognize compressed data, as the1f 8bbuffered streams page does with andmark .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
in a reader processes a compressed log as a stream of lines, without unpacking it to disk first. The same works for large files; seeGZIPInputStreamhandling large files .
The ZIP file system
The JDK includes a file system provider for ZIP files. FileSystems.newFileSystem(zipPath, env)FileSystemFiles
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:
/web/about.html: about us, updated
/web/index.html: home page
archive size on disk: 454 bytes
The archive was created with "create" = "true"ZipOutputStream
Which API to use
| Need | Use |
|---|---|
| Create an archive in one pass | ZipOutputStream |
| List or read selected entries of a file on disk | ZipFile |
| Read an archive from a stream, such as an upload | ZipInputStream |
Modify an existing archive, or use Files | ZIP file system |
| Compress a single stream | GZIPOutputStreamGZIPInputStream |
| Already-compressed media in an archive | STORED |
| Archives from untrusted sources | Path check against zip slip, plus limits on entries and decompressed bytes |
| Archives from old Windows tools | Pass Charset.forName("IBM437") |
| Fast compression of logs or network data | Deflater |