CodeGym /Courses /Kotlin SELF /Working with bytes: readBytes() / writeBytes()

Working with bytes: readBytes() / writeBytes()

Kotlin SELF
Level 43, Lesson 1
Available

1. Introduction

When you’re just starting to work with files, you want simple happiness: “there’s a file, I want to copy it.” And at that moment you learn that files involve streams, buffers, chunked read loops, EOF, and other wonderful words that are convenient for scaring beginners on Halloween. But the truth is that sometimes you don’t need this whole zoo: if the file is small, you can honestly load it into memory as a byte array, and just as honestly write it to another file—no interpretation, no encodings, no complicated loops.

For exactly these scenarios, Kotlin/JVM has a very handy pair: File.readBytes() and File.writeBytes(bytes). They do what their names promise: read and write bytes “as is.” In essence, this is the shortest path from “I have a binary file” to “I have its copy.”

Why this looks like “methods” on File

When you first see code like File("a.bin").readBytes(), it’s easy to think: “Oh, so the File class has a readBytes() method.” And then a second question appears: “Why did the Java File class suddenly get these Kotlin methods?”

The answer is very Kotlin-elegant: these are extension functions.

Kotlin lets you “add” functions to types even if you don’t own their source code. From the outside, they’re called as if they were ordinary methods, but in reality the compiler rewrites this into a call to a regular function. That’s the core idea of extensions: “call it like a member, but we didn’t modify the class.”

Psychologically, this is convenient: file.readBytes() reads almost like a human phrase, not like “call some utility from some package.”

Minimal example: read bytes and print the size

First, let’s make the smallest, most straightforward example: read a file entirely and print how many bytes we got. Here we’re not even copying anything—just verifying that a ByteArray really arrived.

import java.io.File

fun main() {
    val file = File("in.bin")
    val bytes: ByteArray = file.readBytes()

    println("bytesCount=${bytes.size}") // bytesCount=...
}

Note: bytes.size is the number of elements in a ByteArray, i.e., the number of bytes. These are not “characters,” not “lines,” not “letters.” It’s “how many data units are stored in the file.”

2. Whole-file binary copy: “read → write”

Now we do what this was all about: “read → write.” The important point: we do not try to interpret what’s inside the file. We do not turn bytes into text and back. We move them like bricks: “took bricks from box A, put them into box B.”

import java.io.File

fun main() {
    val src = File("in.bin")
    val dst = File("copy.bin")

    val data = src.readBytes()
    dst.writeBytes(data)

    println("copied: ${src.length()} -> ${dst.length()} bytes")
    // copied: 123 -> 123 bytes
}

Here we use length() as a quick indicator of the file size on disk (in bytes). This is not 100% proof that the contents are identical, but it works great as a “first check.”

3. Extract copying into copyBinaryWhole(...)

If you write the “copy” right inside main, then in a couple of days your main will start looking like a vacation to-do list: everything is important, but it’s impossible to read. So let’s extract the copying into a function.

Let’s make a utility for our learning console app (let it be a mini utility FileTool—we’ll build it up neatly in the lectures about files).

import java.io.File

fun copyBinaryWhole(src: File, dst: File) {
    val data = src.readBytes()
    dst.parentFile?.mkdirs() // in case of "out/dir/copy.bin"
    dst.writeBytes(data)
}

fun main() {
    copyBinaryWhole(File("in.bin"), File("out/copy.bin"))
    println("Done") // Done
}

Notice dst.parentFile?.mkdirs(). This is a small bit of future-proofing: if the path is “nested,” the directories may not exist. We’re not diving into robust I/O and exception handling here (that’s a separate big topic), but we’re already getting used to writing code that doesn’t crash “because of a trivial thing.”

4. Result verification: “looks similar” vs “exactly”

Verifying results isn’t paranoia—it’s normal engineering practice. Especially with files: copying can be interrupted, the file can be locked, the disk can run out of space, and you can accidentally mix up paths (and happily overwrite the wrong thing).

It helps to keep two levels of verification in mind:

Check What it proves Pros Cons
src.length() == dst.length()
“Size matches” Fast, doesn’t load memory Contents may differ
src.readBytes().contentEquals(dst.readBytes())
“Byte-for-byte identical” Reliable Both files end up in memory

Size-based check

Let’s start with the simple one: after copying, compare sizes.

import java.io.File

fun main() {
    val src = File("in.bin")
    val dst = File("copy.bin")

    dst.writeBytes(src.readBytes())

    val ok = src.length() == dst.length()
    println("sameSize=$ok") // sameSize=true
}

If sameSize=false, the copy clearly didn’t work. If it’s true, that’s a good sign—but not a guarantee.

Content-based check: contentEquals

To compare two byte arrays by content, you must compare the contents, not “object references.” Kotlin explicitly warns that for arrays you cannot use == as “content comparison,” because arrays are objects, and == for them doesn’t do what many expect. That’s what contentEquals() is for.

import java.io.File

fun main() {
    val a: ByteArray = File("a.bin").readBytes()
    val b: ByteArray = File("b.bin").readBytes()

    println(a.contentEquals(b)) // true or false
}

The key idea: ByteArray is an array, and it’s compared “in a special way.” It’s exactly the same rule as for regular arrays; it’s just especially useful now because we’re working with binary data.

5. Why a == b is not suitable for ByteArray

A very typical beginner situation: “In Kotlin I’m used to == being value comparison. Why doesn’t it work here?” And Kotlin answers: “Because arrays are special.” == checks structural equality for many types, but not for arrays—arrays have dedicated functions contentEquals/contentDeepEquals.

By analogy, a == b for arrays is like asking: “Is this the same package?” (the same object), while contentEquals is: “Are there identical things inside the package, in the same order?” For files and bytes, we almost always care about the latter.

6. Limits of the “whole file” approach: memory is not infinite

This will sound obvious, but it’s useful: RAM is finite. readBytes() reads the entire file into a ByteArray, which means that array has to fit somewhere. If you read a 2–3 GB file this way, the program can very quickly meet OutOfMemoryError (and that meeting is usually without mutual sympathy).

So “read everything” is a tool with a comfort zone: small and medium files. In the next lecture we’ll move on to streams and reading “in chunks,” but even now you can add a simple guard: check the size before reading.

import java.io.File

private const val MAX_BYTES: Long = 10L * 1024 * 1024 // 10 MB

fun main() {
    val file = File("in.bin")

    if (file.length() > MAX_BYTES) {
        println("File is too large: ${file.length()} bytes") // File is too large: ...
        return
    }

    val bytes = file.readBytes()
    println("Loaded ${bytes.size} bytes") // Loaded ...
}

This is not an “ideal strategy,” but it’s an honest and clear barrier: you explicitly tell the code what file size you’re willing to load entirely.

7. Flow: whole copy + verification

So the steps don’t get mixed up in your head, let’s capture the process as a mini flowchart. Yes, programmers love diagrams because they let you think once and then pretend it was obvious for a long time.

flowchart TD
    A[Have a src file] --> B{Is the size acceptable?}
    B -->|no| X[Notify and exit]
    B -->|yes| C["src.readBytes()"]
    C --> D["dst.writeBytes(data)"]
    D --> E{Verify the result}
    E -->|size| F[src.length == dst.length]
    E -->|content| G["data.contentEquals(dst.readBytes())"]

8. FileTool: interactive binary copy

Now we’ll put together a small “practical” piece of code that performs copying and offers a verification option. We’re not going into command-line arguments (that will be on another day of the course), so we’ll implement a simple interactive scenario via readln().

Verification mode selection model

We need to represent the choice “verify by size / verify by content / don’t verify.” For this lecture, a string is enough, but to avoid spreading string magic everywhere, we’ll make a small normalization function.

fun normalizeMode(input: String): String =
    input.trim().lowercase()

We already know trim() and lowercase() from earlier string topics, so everything here should look familiar.

Copy + size verification

First, let’s implement the option that doesn’t require keeping two files in memory.

import java.io.File

fun copyWholeWithSizeCheck(src: File, dst: File): Boolean {
    dst.writeBytes(src.readBytes())
    return src.length() == dst.length()
}

Boolean is convenient here: the function reports “success/failure” as a simple value. We’re not going deep into error design and exceptions—our goal for now is a clear basic scenario.

Copy + content verification

Now the “hard” verification: byte-for-byte comparison via contentEquals, which is designed specifically for content comparison of arrays.

import java.io.File

fun copyWholeWithContentCheck(src: File, dst: File): Boolean {
    val data = src.readBytes()
    dst.writeBytes(data)

    val copied = dst.readBytes()
    return data.contentEquals(copied)
}

Yes, this reads “twice”: once from src, and a second time from dst. That’s fine for a learning example, but keep in mind: on large files this can be expensive.

Assemble main: one scenario, three modes

Now let’s assemble it into a single main. It will be short, but “alive”: it will ask for paths and a verification mode.

import java.io.File

fun main() {
    print("Source file path: ")
    val src = File(readln().trim())

    print("Destination file path: ")
    val dst = File(readln().trim())

    print("Verify mode (none/size/content): ")
    val mode = readln().trim().lowercase()

    val ok = when (mode) {
        "size" -> copyWholeWithSizeCheck(src, dst)
        "content" -> copyWholeWithContentCheck(src, dst)
        else -> { dst.writeBytes(src.readBytes()); true }
    }

    println("OK=$ok") // OK=true (if everything worked)
}

Here when is used as an expression to produce ok. You’ve already covered when earlier in the course, so this should read fine.

Nuance: why in none mode we still return true

The none/else branch in our main performs the copy and says “seems OK.” This is a deliberately simplified option: we don’t verify the result, so we “don’t know,” but for a “just copy it” scenario that’s exactly what the user wanted.

If you want a more honest contract, you could return not a Boolean but, for example, a status string (“COPIED_WITHOUT_VERIFICATION”). But that starts pulling us into designing the operation result, and today our goal is to master readBytes/writeBytes and understand the approach limits.

9. Common mistakes when working with readBytes() / writeBytes()

Mistake #1: reading a binary file as text “out of habit.”
After days of readText() and strings, your hand automatically reaches for reading everything “as a string,” and then you wonder about “garbage characters.” It’s important to ask yourself up front: “Is this text that someone will read with their eyes, or is it bytes (image/archive/executable)?” For binary data, text methods are almost always the wrong tool.

Mistake #2: assuming src.length() == dst.length() guarantees identical content.
Same size is good news, but not proof. Two different files can have the same length. If you need “byte-for-byte identical,” you must compare contents via contentEquals() (and remember that for arrays you can’t rely on ==).

Mistake #3: comparing ByteArray via == and getting weird results.
This is a classic trap: “But in Kotlin == compares values!” Arrays are a special case in Kotlin; there are dedicated functions for content comparison.

Mistake #4: blindly reading huge files entirely.
readBytes() is convenient, but it’s not magic: it will load the whole file into memory. On large files, this becomes a memory and performance risk. Even at this stage it’s useful to get used to checking size via length() and setting a limit, and for large files use a streaming approach (we’ll move to it later per the day plan).

Mistake #5: forgetting about destination directories.
Sometimes you write to a path like out/copy.bin, but the out folder doesn’t exist yet. writeBytes() doesn’t “create the world around it,” it just writes the file. So either create directories in advance, or at least do dst.parentFile?.mkdirs() before writing so you don’t hit errors on flat ground.

1
Task
Kotlin SELF, level 43, lesson 1
Locked
File size
File size
1
Task
Kotlin SELF, level 43, lesson 1
Locked
Reference binary
Reference binary
1
Task
Kotlin SELF, level 43, lesson 1
Locked
Copy to a folder
Copy to a folder
1
Task
Kotlin SELF, level 43, lesson 1
Locked
Checking the copy
Checking the copy
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION