CodeGym /Courses /Kotlin SELF /ZIP archives: ZipEntry, reading/writing

ZIP archives: ZipEntry, reading/writing

Kotlin SELF
Level 43, Lesson 4
Available

1. ZIP as a container on the JVM

When you hear the word “archive”, it’s easy to imagine magic: “somehow it compresses, packs, unpacks”. In practice, it’s more useful to think simpler and a bit more boring (boring thinking is fuel for reliable programs): ZIP is a container, meaning a single file that contains a set of elements. Each element has a name and a byte sequence (file data), and sometimes also a flag meaning “this is a folder”.

So as not to get confused, a small remark for Kotlin fans: the Kotlin standard library has a zip() function for collections (pairwise combining elements). It has nothing to do with ZIP archives other than sharing the same letters.

In Java/Kotlin on the JVM, ZIP is most often processed in a streaming way via classes from java.util.zip. We’ll need three main characters:

What it is Class Role
“An entry description inside an archive”
ZipEntry
Name inside the archive, flags, metadata
“Writing a ZIP”
ZipOutputStream
Add an entry and write bytes into it
“Reading a ZIP”
ZipInputStream
Iterate entries and read the bytes of each one

ZipEntry and names inside the archive

If you imagine a ZIP as a cabinet, then ZipEntry is not the “thing” but the label on the box: what the box is called and what’s inside. In ZipEntry, we’re most interested in name. It’s a string that defines a “path” inside the archive: for example, docs/readme.txt or images/logo.png.

And here is an important point: entry.name looks like a path, but it is not a guarantee that it’s safe to directly turn it into a path on your disk. An archive can contain odd names like ../../secret.txt. In production code, this is checked very strictly. Today we are not building a full security system, but we will still show a careful basic check: we won’t allow escaping the target folder during extraction.

One more nuance: an entry can have a “directory” (folder) flag. In Java this is usually expressed as entry.isDirectory == true (and often the name ends with /). We will take this into account when extracting: a folder must be created, not “written into with bytes”.

2. Writing a ZIP

Action order when adding entries

Writing a ZIP is where beginners most often make the same mistake: they forget that an archive consists of multiple entries, and each entry has “boundaries”.

The correct order for one entry is: create a ZipEntry, call putNextEntry(entry), write bytes, call closeEntry(). If you write multiple files, this cycle repeats for each file.

Diagrammatically, it looks like this:

flowchart TD
    A[ZipOutputStream открыт] --> B["ZipEntry(name)"]
    B --> C["putNextEntry(entry)"]
    C --> D["copyByChunks(fileInput -> zip)"]
    D --> E["closeEntry()"]
    E --> F{ещё файлы?}
    F -->|да| B
    F -->|нет| G[ZipOutputStream закрыт]

Chunk copying: a function that’s convenient to reuse

Before writing a ZIP, you need a “workhorse”: a function that moves bytes from InputStream to OutputStream in blocks.

Note: ByteArray is a fixed-size array, which makes it convenient to reuse as a buffer.

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

fun copyByChunks(input: InputStream, output: OutputStream, bufferSize: Int = 8 * 1024): Long {
    val buffer = ByteArray(bufferSize)
    var total = 0L

    while (true) {
        val n = input.read(buffer)
        if (n == -1) return total
        output.write(buffer, 0, n)
        total += n
    }
}

What matters here is that we write output.write(buffer, 0, n), not the whole buffer. The last block is almost always smaller than the buffer size, and if you write extra bytes, you’ll append a “tail” of old bytes.

The simplest ZIP writing: one file into an archive

A minimal scenario: take the file report.bin and put it into backup.zip under the name report.bin.

import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

fun zipSingleFile(src: File, zipFile: File) {
    ZipOutputStream(FileOutputStream(zipFile)).use { zip ->
        zip.putNextEntry(ZipEntry(src.name))
        FileInputStream(src).use { input -> copyByChunks(input, zip) }
        zip.closeEntry()
    }
}

Notice that copyByChunks(input, zip) works because ZipOutputStream is an OutputStream. For it, writing looks the same as writing “to a regular file”: just bytes.

ZIP from multiple files: a loop with closeEntry()

If we pack multiple files, the main rule does not change: for each file we create a new ZipEntry, call putNextEntry, copy bytes, call closeEntry().

import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

fun zipFiles(files: List<File>, zipFile: File) {
    ZipOutputStream(FileOutputStream(zipFile)).use { zip ->
        for (f in files) {
            zip.putNextEntry(ZipEntry(f.name))
            FileInputStream(f).use { input -> copyByChunks(input, zip) }
            zip.closeEntry()
        }
    }
}

If you want a mini sanity check (without cryptography and hashes), you can at least print the archive size on disk. This doesn’t prove correctness, but it helps you notice an “empty archive” that happened by mistake due to a bug.

import java.io.File

fun main() {
    val zip = File("backup.zip")
    println("zipSize=${zip.length()}") // zipSize=...
}

3. Reading a ZIP and extracting

ZipInputStream, nextEntry, and sequential reading

Reading a ZIP is different from reading a regular directory: ZipInputStream reads an archive sequentially, entry by entry.

Key API: zip.nextEntry. It returns a ZipEntry?. If it returns null, there are no more entries. While an entry is active, zip itself behaves like an InputStream specifically for that entry’s data: you call zip.read(buffer) and get the file bytes.

Mini utility “show what’s inside the archive” (without extracting):

import java.io.FileInputStream
import java.util.zip.ZipInputStream

fun listZip(zipPath: String) {
    ZipInputStream(FileInputStream(zipPath)).use { zip ->
        var entry = zip.nextEntry
        while (entry != null) {
            println("entry=${entry.name}, dir=${entry.isDirectory}")
            zip.closeEntry()
            entry = zip.nextEntry
        }
    }
}

closeEntry() is also important during reading. Even if somewhere it “works anyway”, it’s better to keep discipline: “closed the entry” — “moved to the next one”.

Extraction: directories, parent folders, and a safe path

Extraction is where chunk copying returns to center stage. We take a ZipInputStream, iterate entries, and for each “file” entry create a FileOutputStream in the target directory, then move bytes in blocks: copyByChunks(zip, out).

There are three everyday issues worth solving even in a learning version:

  • First issue — directories. If the entry is a folder, we must create it (mkdirs()), not try to “write bytes into a folder”.
  • Second issue — parent folders of files. If an entry is named docs/readme.txt, then the docs folder must exist. So before writing the file, you need outFile.parentFile?.mkdirs().
  • Third issue — unsafe names. A minimally correct approach: build the final file, normalize/canonicalize the path, and check that it stays inside outDir.
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipInputStream

private fun resolveSafely(outDir: File, entryName: String): File? {
    val target = File(outDir, entryName)
    val outDirCanonical = outDir.canonicalFile
    val targetCanonical = target.canonicalFile

    return if (targetCanonical.path.startsWith(outDirCanonical.path + File.separator)) {
        targetCanonical
    } else {
        null
    }
}

fun unzipAll(zipFile: File, outDir: File) {
    outDir.mkdirs()

    ZipInputStream(FileInputStream(zipFile)).use { zip ->
        var entry = zip.nextEntry
        while (entry != null) {
            val outFile = resolveSafely(outDir, entry.name)

            if (outFile != null) {
                if (entry.isDirectory) {
                    outFile.mkdirs()
                } else {
                    outFile.parentFile?.mkdirs()
                    FileOutputStream(outFile).use { out ->
                        copyByChunks(zip, out)
                    }
                }
            }

            zip.closeEntry()
            entry = zip.nextEntry
        }
    }
}

If you look closely, the code looks almost like “regular copying”, except the input stream for the file is taken not from FileInputStream, but from ZipInputStream, which “currently points to” the current entry’s data.

4. Mini CLI and useful nuances

Commands zip, unzip, list in one main()

When you’re learning, it’s easy to turn a project into a collection of scattered main()s. For practice, it’s more convenient to make a single simple CLI entry point that calls our functions.

We’ll keep parsing as primitive as possible: read a line, split by spaces, take the first words. No “smart” parsing of quotes and spaces in paths — that’s not the goal right now.

import java.io.File

fun main() {
    while (true) {
        print("filelab> ")
        val line = readln().trim()
        if (line.isEmpty()) continue

        val parts = line.split(" ")
        when (parts[0]) {
            "exit" -> return

            "list" -> {
                if (parts.size < 2) println("Usage: list <zipPath>")
                else listZip(parts[1])
            }

            "zip" -> {
                if (parts.size < 3) println("Usage: zip <srcFile> <zipFile>")
                else zipSingleFile(File(parts[1]), File(parts[2]))
            }

            "unzip" -> {
                if (parts.size < 3) println("Usage: unzip <zipFile> <outDir>")
                else unzipAll(File(parts[1]), File(parts[2]))
            }

            else -> println("Unknown command")
        }
    }
}

Nuances: memory and path safety

ZIP as a format can do a lot: compression (different algorithms), passwords (in the real world often poorly compatible), comments, filesystem attributes. We’re not dealing with that. But two “don’t step on rakes” nuances are worth remembering.

First nuance — size and memory. A ZIP can be large, and inside it can contain a file of tens of gigabytes. That’s exactly why ZipInputStream/ZipOutputStream are streaming: they let you avoid holding everything in memory. If you extract an entry by “reading everything into a ByteArray”, you cancel the whole point of streams yourself.

Second nuance — entry names and path safety. Even if your code is “internal”, the habit of mindlessly doing File(outDir, entry.name) sometimes turns into very unpleasant stories. In this lecture we showed a simple practical approach: canonicalize the path and make sure the resulting file is still inside outDir.

5. Common mistakes when working with ZIP archives

Mistake #1: forgetting closeEntry() when writing or reading.
ZIP is a format where entries go one after another, and entry boundaries must be explicitly marked. If you don’t close an entry while writing, the next entry can “merge” with the previous one, and while reading you risk strange behavior when switching between elements. Keep the rule in mind: one entry — one putNextEntry(...) and one closeEntry().

Mistake #2: extracting without creating parent directories.
Entries inside an archive often have “internal folders”, for example docs/readme.txt. If you immediately open FileOutputStream(outFile) and the docs folder doesn’t exist, you’ll get an error for no good reason. The habit of calling outFile.parentFile?.mkdirs() before writing saves a lot of nerves.

Mistake #3: writing output.write(buffer) instead of output.write(buffer, 0, n).
This is classic chunk copying: read(buffer) returns n, and only the first n bytes of the buffer are current. Writing the whole buffer means also writing a “garbage tail” (usually pieces of data from the previous iteration). In archives, this bug is especially nasty: you might get an archive that “was created”, but the files inside will be corrupted.

Mistake #4: assuming entry.name is a “safe path on disk”.
The name inside an archive is just a string. If you directly turn it into a path, the archive can potentially write files “anywhere” relative to your target folder. Even in learning examples, it’s worth at least minimally checking that the resulting path stays inside outDir.

Mistake #5: trying to read a ZIP “entirely into memory” because it’s easier.
Yes, it’s “easier” to write something like zip.readBytes() (or an equivalent) — but this often turns extraction into a memory lottery. The point of streams and buffers is to process data gradually. If the file is small, everything will “seem fine”, and then a larger file arrives and the program suddenly becomes a textbook of OutOfMemoryError mistakes.

1
Task
Kotlin SELF, level 43, lesson 4
Locked
Archive listing
Archive listing
1
Task
Kotlin SELF, level 43, lesson 4
Locked
Zip a file
Zip a file
1
Task
Kotlin SELF, level 43, lesson 4
Locked
Build archive
Build archive
1
Task
Kotlin SELF, level 43, lesson 4
Locked
Unpacking to a directory
Unpacking to a directory
1
Survey/quiz
Binary files, level 43, lesson 4
Unavailable
Binary files
Binary files
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION