Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems
Read and write ZIP and JAR archives in Java: ZipInputStream and ZipOutputStream entry by entry, STORED entries with CRC32, random access with ZipFile, the ZIP file system provider that makes an archive look like a directory, JarOutputStream manifests, and protecting extraction against zip slip.
kvi5hnuCode Sprout team member9 min readOn this page
A ZIP archive packs one or more files, usually compressed, into a single file. Each file in the archive is an entry with a name, such as docs/poem.txt, and metadata such as its size, modification time, checksum and compression method. Java can work with ZIP archives at three levels: as streams of entries, as a random-access ZipFile, and as a complete file system that you use with the ordinary Files methods. JAR files, the archives used to distribute Java programs, are ZIP files too.
Reading with ZipInputStream
ZipInputStream is a filter (article 19) that reads an archive from any input stream, whether a file, a network connection or a byte array. Since an archive holds several files, you walk through the entries one by one:
try (var zin = new ZipInputStream(Files.newInputStream(zipPath))) {
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
byte[] content = zin.readAllBytes(); // the end of input is the end of this entry
process(entry.getName(), content);
zin.closeEntry();
}
}
getNextEntry() positions the stream at the start of the next entry's data and returns its ZipEntry, or null when there are no more. While you're positioned on an entry, zin behaves as if the entry's decompressed contents were the whole stream: reading returns -1 at the entry's end. closeEntry() skips whatever you didn't read, and the next getNextEntry() does that implicitly too. Don't close the ZipInputStream itself until you're done with all the entries.
You can stack other filters on top. For example, new DataInputStream(zin) reads binary values from an entry, and new InputStreamReader(zin, UTF_8) reads text. The decompression happens transparently as bytes are requested. That's the stream abstraction at its best.
Since ZipInputStream reads sequentially, some entry metadata may not be known until the entry's data has been read. Directory entries have names ending in /, and isDirectory() tests for that.
Writing with ZipOutputStream
To create an archive, make a ZipEntry for each file, start it with putNextEntry, write its data, and close it with closeEntry:
try (var zout = new ZipOutputStream(Files.newOutputStream(zipPath))) {
for (Path file : files) {
zout.putNextEntry(new ZipEntry(file.getFileName().toString()));
Files.copy(file, zout);
zout.closeEntry();
}
}
The ZipEntry constructor takes the name, using / as the separator on every platform. The other properties get defaults: the current time, and the compression method of the stream, DEFLATED unless changed. setLevel chooses the compression level from Deflater.NO_COMPRESSION (0) to Deflater.BEST_COMPRESSION (9). To get reproducible archives, for example in builds, set a fixed time on each entry with setTimeLocal or setLastModifiedTime.
An entry can also be STORED without compression, which makes sense for data that is already compressed, such as JPEG images. For a stored entry, you must set the size and the CRC-32 checksum before writing the data, because the format puts them in the entry header:
var crc = new CRC32();
crc.update(bytes);
var entry = new ZipEntry("photo.jpg");
entry.setMethod(ZipEntry.STORED);
entry.setSize(bytes.length);
entry.setCrc(crc.getValue());
Random access with ZipFile
A ZIP file has a central directory at its end that lists all entries. ZipInputStream ignores it and reads front to back. java.util.zip.ZipFile reads the central directory and gives you direct access to any entry, which is faster when you need only a few:
try (var zf = new ZipFile(zipPath.toFile())) {
ZipEntry e = zf.getEntry("docs/poem.txt");
try (InputStream in = zf.getInputStream(e)) { ... }
zf.stream().forEach(entry -> ...); // all entries
}
ZipFile works only with files, not with arbitrary input streams. It also knows every entry's sizes up front: getSize() for the uncompressed and getCompressedSize() for the compressed size.
ZIP file systems
The nicest way to work with archives is the ZIP file system provider. It makes an archive look like a directory tree, so you can use Path and Files (articles 25 to 28) with no ZIP-specific API at all:
try (FileSystem fs = FileSystems.newFileSystem(zipPath)) {
Files.copy(fs.getPath("/docs/poem.txt"), targetPath); // extract one file
try (Stream<Path> paths = Files.walk(fs.getPath("/"))) { // list everything
paths.forEach(System.out::println);
}
}
fs.getPath is the counterpart of Path.of for a particular file system. Paths from the ZIP file system and the default file system can be mixed in Files.copy and Files.move.
To create an archive, pass the "create" option, then write into the file system. The archive is written out when you close the file system:
try (FileSystem fs = FileSystems.newFileSystem(zipPath, Map.of("create", "true"))) {
Files.createDirectories(fs.getPath("/notes"));
Files.writeString(fs.getPath("/notes/todo.txt"), "learn NIO\n");
}
You can also open the archive through a jar: URI such as jar:file:///tmp/created.zip with FileSystems.newFileSystem(uri, env). The provider handles names ending in .zip and .jar and anything else you point it at explicitly. Other options in the environment map include "compressionMethod" ("STORED" or "DEFLATED") and "releaseVersion" for multi-release JARs.
JAR files
A JAR file is a ZIP file with a special entry META-INF/MANIFEST.MF that describes the archive, for example its main class (Volume I, Part 4). JarOutputStream takes a Manifest and writes it as the first entry. JarInputStream and JarFile give you the manifest back with getManifest(). Everything else works as with ZIP.
A complete example
import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.jar.*;
import java.util.stream.*;
import java.util.zip.*;
public class Solution {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("zipdemo");
Path zip = dir.resolve("test.zip");
String poem = "Twinkle, twinkle, little star,\n".repeat(50);
// writing a ZIP archive entry by entry
try (var zout = new ZipOutputStream(Files.newOutputStream(zip))) {
zout.putNextEntry(new ZipEntry("docs/")); // a directory entry
zout.closeEntry();
zout.putNextEntry(new ZipEntry("docs/poem.txt"));
zout.write(poem.getBytes(StandardCharsets.UTF_8));
zout.closeEntry();
// a STORED (uncompressed) entry needs its size and CRC up front
byte[] raw = { 1, 2, 3, 4, 5 };
var crc = new CRC32();
crc.update(raw);
var stored = new ZipEntry("data.bin");
stored.setMethod(ZipEntry.STORED);
stored.setSize(raw.length);
stored.setCrc(crc.getValue());
zout.putNextEntry(stored);
zout.write(raw);
zout.closeEntry();
}
// reading it sequentially
try (var zin = new ZipInputStream(Files.newInputStream(zip))) {
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
byte[] content = zin.readAllBytes(); // reads to the end of this entry only
System.out.println(entry.getName() + (entry.isDirectory() ? " (directory)" : ": " + content.length
+ " bytes, " + (entry.getMethod() == ZipEntry.STORED ? "stored" : "deflated")));
zin.closeEntry();
}
}
// ZipFile gives random access to the entries
try (var zf = new ZipFile(zip.toFile())) {
ZipEntry e = zf.getEntry("docs/poem.txt");
System.out.println("size " + e.getSize() + ", compressed smaller: " + (e.getCompressedSize() < e.getSize()));
try (InputStream in = zf.getInputStream(e)) {
System.out.println("first line: " + new String(in.readAllBytes(), StandardCharsets.UTF_8).lines().findFirst().orElse(""));
}
System.out.println("entries: " + zf.stream().map(ZipEntry::getName).toList());
}
// a ZIP file system: the archive looks like a directory tree
try (FileSystem fs = FileSystems.newFileSystem(zip)) {
try (Stream<Path> paths = Files.walk(fs.getPath("/"))) {
System.out.println("walk: " + paths.map(Path::toString).sorted().toList());
}
Path extracted = dir.resolve("poem-copy.txt");
Files.copy(fs.getPath("/docs/poem.txt"), extracted);
System.out.println("extracted lines: " + Files.readAllLines(extracted).size());
}
// creating a new archive through a ZIP file system
Path created = dir.resolve("created.zip");
try (FileSystem fs = FileSystems.newFileSystem(created, Map.of("create", "true"))) {
Files.createDirectories(fs.getPath("/notes"));
Files.writeString(fs.getPath("/notes/todo.txt"), "learn NIO\n");
Files.copy(dir.resolve("poem-copy.txt"), fs.getPath("/poem.txt"));
} // closing writes the archive
try (var zf = new ZipFile(created.toFile())) {
System.out.println("created.zip: " + zf.stream().map(ZipEntry::getName).sorted().toList());
}
// the same through a jar: URI
URI uri = URI.create("jar:" + created.toUri());
try (FileSystem fs = FileSystems.newFileSystem(uri, Map.of())) {
System.out.println("todo: " + Files.readString(fs.getPath("/notes/todo.txt")).strip());
}
// JAR files are ZIP files with a manifest
Path jar = dir.resolve("app.jar");
var manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, "com.example.Main");
try (var jout = new JarOutputStream(Files.newOutputStream(jar), manifest)) {
jout.putNextEntry(new JarEntry("README.txt"));
jout.write("hello".getBytes(StandardCharsets.UTF_8));
jout.closeEntry();
}
try (var jf = new JarFile(jar.toFile())) {
System.out.println("Main-Class: " + jf.getManifest().getMainAttributes().getValue(Attributes.Name.MAIN_CLASS));
System.out.println("jar entries: " + jf.stream().map(JarEntry::getName).toList());
}
// guarding against "zip slip" when extracting
Path target = dir.resolve("out");
for (String name : List.of("docs/poem.txt", "../../etc/passwd")) {
Path dest = target.resolve(name).normalize();
System.out.println(name + " -> " + (dest.startsWith(target) ? "safe" : "REJECTED, escapes the target directory"));
}
// clean up
try (Stream<Path> paths = Files.walk(dir)) {
paths.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
}
}
}
docs/ (directory)
docs/poem.txt: 1550 bytes, deflated
data.bin: 5 bytes, stored
size 1550, compressed smaller: true
first line: Twinkle, twinkle, little star,
entries: [docs/, docs/poem.txt, data.bin]
walk: [/, /data.bin, /docs, /docs/poem.txt]
extracted lines: 50
created.zip: [notes/, notes/todo.txt, poem.txt]
todo: learn NIO
Main-Class: com.example.Main
jar entries: [META-INF/MANIFEST.MF, README.txt]
docs/poem.txt -> safe
../../etc/passwd -> REJECTED, escapes the target directory
The demo works in a temporary directory and deletes it at the end. Compressed sizes depend on the zlib version, so they're only compared, not printed.
Common questions
How do I zip a whole directory?
Walk the directory with Files.walk (article 28) and copy every regular file into a ZIP file system, creating the parent directories inside the archive with Files.createDirectories. Alternatively, write each file with ZipOutputStream, using the path relativized against the source directory, with / separators, as the entry name.
Can Java create or open password-protected ZIP files? Not with the JDK. Neither the classic ZIP encryption nor AES-encrypted entries are supported. Use a library such as zip4j, or encrypt the whole archive with the JCA classes from Part 9.
What about .gz and .tar.gz files?
GZIPInputStream and GZIPOutputStream handle .gz, which compresses a single stream of bytes. TAR is a different archive format with no JDK support, so a .tar.gz needs a library such as Apache Commons Compress for the TAR part.
Entry names with accented characters come out garbled. Why?
Old ZIP tools stored names in a legacy code page instead of UTF-8. Java assumes UTF-8 unless the archive says otherwise. Pass the right charset to the constructor, as in new ZipInputStream(in, Charset.forName("IBM437")) or new ZipFile(file, charset), or set "encoding" in the ZIP file system's environment map.
Can I add or replace a file in an existing archive?
Yes, with the ZIP file system: open it without "create", then Files.copy(source, fs.getPath("/new.txt"), REPLACE_EXISTING). The provider rewrites the archive when you close the file system. With ZipOutputStream, you would have to copy all entries into a new archive.
Is it safe to extract archives uploaded by users? Only with the zip slip check, limits on total size and entry count, and ideally a separate directory per upload. Never trust the sizes declared in the archive; count the bytes you actually write.
API reference
java.util.zip.ZipInputStream
| Method | Description |
|---|---|
ZipInputStream(InputStream in), ZipInputStream(InputStream in, Charset charset) | reads an archive; charset decodes entry names (UTF-8 by default) |
ZipEntry getNextEntry() | moves to the next entry, or returns null at the end |
void closeEntry() | skips the rest of the current entry |
java.util.zip.ZipOutputStream
| Method | Description |
|---|---|
ZipOutputStream(OutputStream out) | writes an archive to out |
void putNextEntry(ZipEntry e) | starts a new entry; write its data next |
void closeEntry() | finishes the current entry |
void setLevel(int level) | compression level, Deflater.NO_COMPRESSION to BEST_COMPRESSION |
void setMethod(int method) | default method for new entries: ZipOutputStream.DEFLATED or STORED |
java.util.zip.ZipEntry
| Method | Description |
|---|---|
ZipEntry(String name) | an entry with the given name (/-separated) |
String getName(), boolean isDirectory() | the name, and whether it ends in / |
long getSize(), long getCompressedSize(), long getCrc() | sizes and CRC-32 checksum, or -1 if unknown |
void setMethod(int method), setSize(long size), setCrc(long crc) | method, and size and CRC (required for STORED) |
void setTimeLocal(LocalDateTime time) (Java 9) | sets the modification time |
java.util.zip.ZipFile
| Method | Description |
|---|---|
ZipFile(File file), ZipFile(String name) | opens an archive for random access |
ZipEntry getEntry(String name) | the entry with the given name, or null |
InputStream getInputStream(ZipEntry entry) | the decompressed contents of an entry |
Stream<? extends ZipEntry> stream() | all entries |
java.nio.file.FileSystems
| Method | Description |
|---|---|
static FileSystem newFileSystem(Path path), newFileSystem(Path path, Map<String, ?> env) (Java 13) | opens a file system for a file such as a ZIP archive; env can hold "create" |
static FileSystem newFileSystem(URI uri, Map<String, ?> env) | opens a file system for a jar: URI |
java.nio.file.FileSystem
| Method | Description |
|---|---|
Path getPath(String first, String... more) | a path in this file system |
void close() | closes the file system, writing changes to the archive |
Summary
ZipInputStreamreads archives entry by entry from any stream:getNextEntry, read until -1,closeEntry.ZipOutputStreamwrites them:putNextEntry, write the data,closeEntry. STORED entries need their size and CRC set first.ZipFileuses the archive's central directory for random access to entries in a file.- The ZIP file system provider lets you use
PathandFilesinside an archive. Create archives withMap.of("create", "true"), and close the file system to save. - JAR files are ZIP files with a manifest, handled by
JarOutputStream,JarInputStreamandJarFile. - When extracting, normalize entry paths and reject any outside the target directory (zip slip), and limit extracted sizes (zip bombs).
Practice Questions
Inside the getNextEntry loop, what does zin.readAllBytes() return?
Only the decompressed contents of the current entry. The ZipInputStream reports the end of input at the end of each entry, and the next getNextEntry() call moves on to the following one.
Why does a STORED entry need its size and CRC before the data is written, while a DEFLATED entry doesn't?
For STORED entries, the size and checksum go into the local header in front of the data, and readers rely on them to find where the data ends. For DEFLATED entries, ZipOutputStream can write them after the data in a "data descriptor", since the compressed stream marks its own end.
How do you extract the single file images/logo.png from a large archive most efficiently?
Use random access instead of reading the whole archive. Either zipFile.getInputStream(zipFile.getEntry("images/logo.png")), or open a ZIP file system and call Files.copy(fs.getPath("/images/logo.png"), target).
You add files to a ZIP file system, but the archive on disk stays unchanged. What's missing?
The file system was never closed. The ZIP provider writes the archive when close() is called, so use try-with-resources around FileSystems.newFileSystem.
An uploaded archive contains the entry ../../app/config.properties. How does your extraction code protect against it?
Normalize the target once (target = target.toAbsolutePath().normalize();), then resolve and normalize each entry: Path dest = target.resolve(name).normalize();, and reject the entry unless dest.startsWith(target). Here the normalized path leaves the target directory, so it's rejected.
Previous: Java RandomAccessFile: Seeking and Fixed-Size Records
Next: Java NIO Path: Creating, Resolving, Relativizing and Normalizing Paths
Related reading
- Java I/O Filters: Buffered, Data and Pushback Streams
- Java I/O Streams: Reading and Writing Bytes
- Java Parallel Streams: When They Help, Ordering and Thread Safety
- Java Primitive Streams: IntStream, LongStream and DoubleStream
- Implementing Java Stream Gatherers: Integrators, State, Short-Circuiting and Parallelism

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.