ZIP archives

suggest change

ZIP is the most widely used archive format: downloads, backups, data exports, .jar, .docx, .xlsx and .apk files are all ZIP archives. Kotlin on the JVM doesn't need a library for it, because java.util.zip and the ZIP file system provider ship with the JDK.

This article covers:

All examples use only the JDK and the Kotlin standard library.

The main classes

Class Use it for
ZipOutputStream writing a new archive, entry by entry, to any OutputStream
ZipInputStream reading entries in order from any InputStream (file, network, memory)
ZipFile random access to an archive on disk, using its central directory
ZipEntry metadata of one entry: name, size, compressed size, CRC, time, method
FileSystems.newFileSystem treating an archive as a directory tree you can read and modify with Files

Creating an archive

Open a ZipOutputStream, then for each file call putNextEntry, write the bytes and call closeEntry. Entry names use / as the separator on every OS, and a name ending with / is a directory:

import java.nio.file.Path
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.io.path.outputStream

fun main() {
    val zipPath = Path.of("example.zip")
    ZipOutputStream(zipPath.outputStream().buffered()).use { zip ->
        zip.putNextEntry(ZipEntry("hello.txt"))
        zip.write("Hello, ZIP!\n".toByteArray())
        zip.closeEntry()

        zip.putNextEntry(ZipEntry("logs/"))   // explicit directory entry (optional)
        zip.closeEntry()

        zip.putNextEntry(ZipEntry("logs/app.log"))
        zip.write("INFO request handled\n".repeat(500).toByteArray())
        zip.closeEntry()
    }
    println("Created $zipPath")
}
Created example.zip

use closes the stream even if an exception is thrown. Closing is essential: the central directory (the index at the end of the file) is written by close() / finish(), and without it the archive is corrupt.

Directory entries are optional. Most tools create the directories implied by logs/app.log on extraction anyway, but adding them preserves empty directories.

If the data already lives in a file, stream it instead of loading it into memory:

zip.putNextEntry(ZipEntry("data/report.csv"))
Path.of("report.csv").inputStream().use { it.copyTo(zip) }
zip.closeEntry()

Listing entries with ZipFile

ZipFile reads the central directory, so it knows every entry's size and compressed size up front and can open any entry without scanning the whole file:

import java.util.zip.ZipFile

fun main() {
    ZipFile("example.zip").use { zf ->
        for (entry in zf.entries()) {
            val kind = if (entry.isDirectory) "dir " else "file"
            println("$kind ${entry.name.padEnd(14)} size=${entry.size} compressed=${entry.compressedSize}")
        }

        val hello = zf.getEntry("hello.txt") ?: error("missing hello.txt")
        val text = zf.getInputStream(hello).bufferedReader().use { it.readText() }
        print("hello.txt: $text")
    }
}
file hello.txt      size=12 compressed=14
dir  logs/          size=0 compressed=2
file logs/app.log   size=10500 compressed=71
hello.txt: Hello, ZIP!

A few notes:

Prefer ZipFile whenever the archive is a file on disk.

Reading sequentially with ZipInputStream

ZipInputStream reads entries in the order they appear in the stream. It works on any InputStream, so you can process an archive while it downloads, or one held in a ByteArray. nextEntry returns null after the last entry, and reading from the stream returns the bytes of the current entry only:

import java.nio.file.Path
import java.util.zip.ZipInputStream
import kotlin.io.path.inputStream

fun main() {
    ZipInputStream(Path.of("example.zip").inputStream().buffered()).use { zin ->
        while (true) {
            val entry = zin.nextEntry ?: break
            if (entry.isDirectory) continue
            val sizeField = entry.size       // read before the data
            val bytes = zin.readBytes()      // reads until the end of this entry
            println("${entry.name}: ${bytes.size} bytes, size field = $sizeField")
        }
    }
}
hello.txt: 12 bytes, size field = -1
logs/app.log: 10500 bytes, size field = -1

Note size field = -1. When ZipOutputStream writes a compressed entry to a stream, it doesn't know the sizes in advance, so it writes them in a "data descriptor" after the data. A streaming reader sees the entry header first, so size, compressedSize and crc are unknown (-1) until you've read the entry. Never use entry.size from ZipInputStream to size a buffer.

Zipping a directory

Walk the tree, compute each file's path relative to the root, and convert it to a /-separated entry name. On Windows Path.toString() uses \, which produces broken archives on other systems:

import java.nio.file.Files
import java.nio.file.Path
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.io.path.*

fun zipDirectory(sourceDir: Path, zipPath: Path) {
    ZipOutputStream(zipPath.outputStream().buffered()).use { zip ->
        Files.walk(sourceDir).use { paths ->
            paths.filter { it != sourceDir }.sorted().forEach { path ->
                val name = sourceDir.relativize(path).invariantSeparatorsPathString
                if (path.isDirectory()) {
                    zip.putNextEntry(ZipEntry("$name/"))
                    zip.closeEntry()
                } else {
                    val entry = ZipEntry(name)
                    entry.setLastModifiedTime(path.getLastModifiedTime())
                    zip.putNextEntry(entry)
                    path.inputStream().use { it.copyTo(zip) }
                    zip.closeEntry()
                }
            }
        }
    }
}

fun main() {
    val src = Path.of("site")
    (src / "css").createDirectories()
    (src / "index.html").writeText("<h1>Hi</h1>")
    (src / "css" / "style.css").writeText("h1 { color: red; }")

    zipDirectory(src, Path.of("site.zip"))
    java.util.zip.ZipFile("site.zip").use { zf ->
        zf.entries().asSequence().forEach { println(it.name) }
    }
}
css/
css/style.css
index.html

invariantSeparatorsPathString (from kotlin.io.path) always uses /. Files.walk returns a Stream that holds open directory handles, so it must be closed, which use does. Sorting makes the archive deterministic, which is nice for builds and tests.

Extracting safely (zip slip)

Entry names come from whoever created the archive. A malicious archive can contain names like ../../.bashrc or /etc/cron.d/job, and naive code writes outside the target directory. This is called zip slip. Always resolve the name, normalize it, and check that the result is still inside the destination:

import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.zip.ZipFile
import kotlin.io.path.*

fun unzip(zipPath: Path, destDir: Path) {
    val root = destDir.toAbsolutePath().normalize()
    root.createDirectories()
    ZipFile(zipPath.toFile()).use { zf ->
        for (entry in zf.entries()) {
            val target = root.resolve(entry.name).normalize()
            if (!target.startsWith(root)) {
                throw SecurityException("Entry is outside of target dir: ${entry.name}")
            }
            if (entry.isDirectory) {
                target.createDirectories()
            } else {
                target.parent?.createDirectories()
                zf.getInputStream(entry).use { input ->
                    java.nio.file.Files.copy(input, target, StandardCopyOption.REPLACE_EXISTING)
                }
            }
        }
    }
}

fun main() {
    unzip(Path.of("site.zip"), Path.of("out"))
    println(Path.of("out/css/style.css").readText())
}
h1 { color: red; }

Path.startsWith compares path components, not strings, so /tmp/out2 does not count as inside /tmp/out. The parent?.createDirectories() call matters because many archives have no directory entries at all.

Limiting decompressed size (zip bombs)

A tiny archive can expand to gigabytes. If you extract archives uploaded by users, cap the total number of bytes and entries, counting what you actually read rather than trusting entry.size:

import java.io.InputStream
import java.io.OutputStream

fun copyLimited(input: InputStream, output: OutputStream, budget: LongArray) {
    val buf = ByteArray(8192)
    while (true) {
        val n = input.read(buf)
        if (n < 0) break
        budget[0] -= n
        if (budget[0] < 0) throw IllegalStateException("Archive expands beyond the allowed size")
        output.write(buf, 0, n)
    }
}

Create val budget = longArrayOf(100L * 1024 * 1024) once per archive and use copyLimited instead of Files.copy in unzip.

Creating a ZIP in memory

ZipOutputStream writes to any OutputStream, so a ByteArrayOutputStream gives you the archive as a ByteArray, ready to return from an HTTP handler or store in a database:

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream

fun zipOf(files: Map<String, String>): ByteArray {
    val bytes = ByteArrayOutputStream()
    ZipOutputStream(bytes).use { zip ->
        for ((name, content) in files) {
            zip.putNextEntry(ZipEntry(name))
            zip.write(content.toByteArray())
            zip.closeEntry()
        }
    }   // the archive is complete only after close()
    return bytes.toByteArray()
}

fun unzipToMap(data: ByteArray): Map<String, String> = buildMap {
    ZipInputStream(ByteArrayInputStream(data)).use { zin ->
        generateSequence { zin.nextEntry }
            .filterNot { it.isDirectory }
            .forEach { put(it.name, zin.readBytes().decodeToString()) }
    }
}

fun main() {
    val data = zipOf(mapOf("a.txt" to "alpha", "b/c.txt" to "charlie"))
    println("First bytes: ${data.take(4).joinToString(" ") { "%02X".format(it) }}")
    println(unzipToMap(data))
}
First bytes: 50 4B 03 04
{a.txt=alpha, b/c.txt=charlie}

Every ZIP starts with the signature PK\u0003\u0004 (50 4B 03 04), after Phil Katz, the format's author. Call bytes.toByteArray() only after the ZipOutputStream is closed, otherwise you get an archive without its central directory.

For an HTTP response, set Content-Type: application/zip and Content-Disposition: attachment; filename="export.zip", and write the ZipOutputStream directly to the response output stream so large exports don't have to fit in memory.

Modifying an archive with the ZIP file system

ZipOutputStream can only create new archives. To add, replace or delete entries in an existing one, open it as a FileSystem and use the normal Files / kotlin.io.path API. Changes are written when the file system is closed:

import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.*

fun main() {
    val zipPath = Path.of("notes.zip")
    zipPath.deleteIfExists()

    // "create" = "true" creates the archive if it doesn't exist (Java 13+ overload)
    FileSystems.newFileSystem(zipPath, mapOf("create" to "true")).use { fs ->
        fs.getPath("/todo.txt").writeText("buy milk\n")
        fs.getPath("/archive").createDirectories()
        fs.getPath("/archive/old.txt").writeText("done\n")
    }

    FileSystems.newFileSystem(zipPath).use { fs ->
        fs.getPath("/todo.txt").appendText("write article\n")
        fs.getPath("/archive/old.txt").deleteExisting()
        Files.copy(fs.getPath("/todo.txt"), fs.getPath("/todo-backup.txt"))
    }

    FileSystems.newFileSystem(zipPath).use { fs ->
        Files.walk(fs.getPath("/")).use { paths ->
            paths.filter { it.isRegularFile() }.sorted().forEach { println("$it: ${it.readText().trim().replace("\n", " | ")}") }
        }
    }
}
/todo-backup.txt: buy milk | write article
/todo.txt: buy milk | write article

The ZIP file system rewrites the whole archive on close, so it's convenient for small edits but not the fastest choice for large archives. On Java 8 to 12, use the URI form: FileSystems.newFileSystem(URI.create("jar:" + zipPath.toUri()), mapOf("create" to "true")).

Compression level and STORED entries

Use setLevel to trade speed for size, from Deflater.NO_COMPRESSION (0) to Deflater.BEST_COMPRESSION (9). The default is 6:

ZipOutputStream(out).use { zip ->
    zip.setLevel(java.util.zip.Deflater.BEST_SPEED)
    zip.setComment("Nightly export")
    // ...
}

Already-compressed data (JPEG, PNG, MP4, other ZIPs) doesn't shrink. Store it uncompressed with ZipEntry.STORED. For stored entries ZipOutputStream writes sizes and CRC in the entry header, so you must set them before putNextEntry, or you get ZipException: STORED entry missing size, compressed size, or crc-32:

import java.util.zip.CRC32
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

fun ZipOutputStream.putStored(name: String, data: ByteArray) {
    val entry = ZipEntry(name).apply {
        method = ZipEntry.STORED
        size = data.size.toLong()
        compressedSize = data.size.toLong()
        crc = CRC32().apply { update(data) }.value
    }
    putNextEntry(entry)
    write(data)
    closeEntry()
}

This is also how you build EPUB files, whose first entry must be an uncompressed mimetype file.

File names and encodings

ZipOutputStream writes names as UTF-8 and sets the "language encoding" flag, and ZipFile / ZipInputStream read UTF-8 by default. Old archives created by Windows tools often use the DOS code page instead; reading them as UTF-8 throws ZipException: invalid CEN header (bad entry name) or produces garbled names. Pass the charset explicitly:

import java.nio.charset.Charset
import java.util.zip.ZipFile

val zf = ZipFile(java.io.File("legacy.zip"), Charset.forName("CP437"))

ZipInputStream(input, charset) and ZipOutputStream(output, charset) accept a charset the same way.

Gotchas

For writing scratch archives during processing or tests, see Temporary files.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents