CodeGym /Courses /Kotlin SELF /use {} for I/O: closing files correctly

use {} for I/O: closing files correctly

Kotlin SELF
Level 42, Lesson 4
Available

1. Resource: why a file must be closed

When you read a file via readText() or readLines(), it can feel like magic on the level of “just give me a string.” But under the hood, something very “physical” happens: the operating system allocates a resource to your process—an open file descriptor/stream. While the resource is open, the OS maintains the “program ↔ file” connection and expects the program to politely say: “I’m done; you can close it.”

A resource has an unpleasant property: if you don’t close it, it won’t disappear “by itself” exactly when it’s convenient for you. It may close later (when the garbage collector runs), or it may not close quickly enough for it to become a problem right now. That’s why working with files is always about discipline: opened → used → closed, preferably without the “oops, I forgot.”

To make the idea stick visually, you can think of it like this:

flowchart TD
    A["Opened a file (Reader/Writer/Stream)"] --> B["Read / wrote data"]
    B --> C["Closed the resource (close)"]
    B -->|If an error occurred| D["Exception"]
    D --> C

The main point: closing must happen both on “success” and on “failure.”

2. Two approaches to closing resources

Manual close()

At the beginning it’s easy to believe you can do this: open a BufferedReader, read, then call close() at the end. On paper everything looks nice. In real code, “branching destinies” begin: early return, exceptions, break, continue, another return, because “well there’s an error, why continue.”

And then in some branch you exit the function earlier than the point where you reach close(). Or an exception suddenly flies in during reading—and close() is not called either. As a result the file stays open, and you look at the error and think: “Someone stole my descriptor, but who?”

A reliable but more “verbose” approach is try/finally. It guarantees that finally runs even when an exception happens, and that’s a fundamental idea.

Mini example on a “training resource”:

class FakeResource {
    fun work() {
        println("Working...") // Working...
        error("Boom")         // simulate a failure
    }

    fun close() {
        println("Closed")     // Closed
    }
}

fun main() {
    val r = FakeResource()
    try {
        r.work()
    } finally {
        r.close()
    }
}

Does it work? Yes. Is it pretty? Let’s say it’s like carrying a screwdriver to open a bottle. You can, but you want a “button.”

That “button” in Kotlin is use { ... }.

use {}: what it is and what guarantee it provides

use { ... } is Kotlin’s idiomatic approach (like Java’s try-with-resources, just without separate syntax). The meaning is the same: you give Kotlin a resource and a block of code; Kotlin executes the block and then automatically closes the resource—regardless of whether the block finished normally or threw an exception.

One more important detail: use is a generic (generic) function applicable to closable resources. That is, it works for types that satisfy the “closable” contract (for example, Closeable).

Psychologically, it’s convenient to read this code as: “here is a resource, use it in the block, then close it.”

Comparison of try/finally and use (not as “better/worse,” but as “what you type by hand”):

What we do
try/finally
use {}
Guarantee closing Yes Yes
More code Usually yes Usually no
Where closing happens In finally Automatically after the block
Risk of “forgot close” There is Almost none (if you immediately write .use { ... })

Mini example with a real file (idea only, without error handling):

import java.io.File

fun main() {
    val firstLine = File("data/input.txt")
        .bufferedReader()
        .use { br -> br.readLine() }

    println(firstLine) // for example: Hello
}

Here BufferedReader will be closed automatically after leaving the use block.

3. Reading a file via bufferedReader().use { ... }

Before today, you’ve already read files using “short methods” like readText() and readLines(). They’re great when the file is small and you truly want to load its entire contents into memory. But as soon as the idea “read gradually” appears (for example, find the first matching line or compute statistics), it’s more convenient to open a reader and read line by line.

That’s what bufferedReader() is for: it gives you an object that has readLine(). And to avoid thinking about closing—wrap it in use right away.

Example: read the first non-blank line

import java.io.File

fun main() {
    val firstNonBlank = File("data/input.txt").bufferedReader().use { br ->
        var line: String?
        while (true) {
            line = br.readLine() ?: break
            if (line.isNotBlank()) return@use line.trim()
        }
        null
    }

    println(firstNonBlank) // for example: Title
}

Notice return@use: this is a “return from the lambda,” not from main. I intentionally use a label to make the behavior as explicit as possible, even if you already know about inline and non-local return.

Example: count lines without loading the entire file

import java.io.File

fun main() {
    val count = File("data/input.txt").bufferedReader().use { br ->
        var lines = 0
        while (br.readLine() != null) lines++
        lines
    }

    println("lines=$count") // lines=42
}

Key style: inside use we do only work with the reader. Once you start building half of the application’s business logic inside use, the code becomes harder to read and debug. use is a “short corridor to the resource,” not a “3-hour meeting room.”

4. Writing a file via bufferedWriter().use { ... }

writeText() and appendText() are also fine: they’re short and clear. But sometimes you want to write in chunks: a header, then lines, then a summary, then a newline. You can concatenate strings ahead of time (for example, using StringBuilder), but sometimes it’s simpler and more honest to write as you generate.

Then it’s convenient to take bufferedWriter() and again wrap it in use. In Kotlin, use closes the resource automatically, and closing a writer usually includes a final “flush” of the buffer (you don’t need to call flush() manually in training examples). The idea “closed means definitely written” is very pleasant here.

Example: write a small report line by line.

import java.io.File

fun main() {
    val out = File("data/reports/summary.txt")
    out.parentFile?.mkdirs()

    out.bufferedWriter().use { w ->
        w.write("Report\n")
        w.write("items=3\n")
        w.write("ok=true\n")
    }
}

If an exception suddenly happens during writing, use will still try to close the writer. That’s exactly the “cleanup on failure” guarantee we started this whole lecture for.

A separate nuance about line breaks: write() doesn’t add "\n" by itself, so you control the format manually. That’s good: there will be no “magic” newlines, but the responsibility is yours (yes, a programmer is a person who places "\n" themselves so they don’t cry later).

5. useLines{}: lazy lines and block boundaries

Sometimes you want the convenience of line-by-line processing, but without manual BufferedReader and a while. That’s what useLines { ... } is for. It opens the file, gives you a “stream of lines” (conceptually a lazy sequence), and after the block completes it reliably closes the file.

It’s like: “I want to work with lines like with a collection, but I don’t want to keep the whole file in memory.” Inside the block you usually do something like count, filter, map, firstOrNull, and so on—and get a final value.

Example: count non-blank lines.

import java.io.File

fun main() {
    val nonBlank = File("data/input.txt").useLines { lines ->
        lines.count { it.isNotBlank() }
    }

    println("nonBlank=$nonBlank") // nonBlank=10
}

Example: find the first line that looks like a header (for example, starts with "#").

import java.io.File

fun main() {
    val header = File("data/input.txt").useLines { lines ->
        lines.firstOrNull { it.trim().startsWith("#") }
    }

    println(header) // for example: # Shopping list
}

Now—the most important thought, worth pausing for.

useLines closes the file after the block. That means you can’t honestly return the “lines” outward and keep reading them later—the file is already closed. This is a typical logical mistake: you seem to have “returned a Sequence,” but a Sequence has no data “inside”; it pulls them from the file during iteration. And by that moment the file has already been closed.

The correct strategy is simple: either do the computation inside useLines and return a finished result (number/string/list), or use readLines() if you truly need a list of lines in memory.

6. Practical example: saving and loading expenses

From this point on, in a training application it becomes natural to introduce the simplest text storage. Not a “database,” not an “ideal format,” but an honest file that you can open in a text editor and understand with your eyes. We won’t discuss encodings and complex formats—today the goal is precisely safe I/O style.

Let’s assume that the project already has an expense model:

data class Expense(
    val amount: Int,
    val category: String,
    val note: String
)

Let’s make a very simple line format: "amount;category;note". Yes, a semicolon is not “ideal,” but it’s easy to parse with split(";").

Serialization (object → string):

fun serializeExpense(e: Expense): String {
    val safeNote = e.note.replace(";", ",")
    return "${e.amount};${e.category};$safeNote"
}

Parsing (string → object or null if the line is broken):

fun parseExpenseOrNull(line: String): Expense? {
    val parts = line.split(";")
    if (parts.size < 3) return null

    val amount = parts[0].toIntOrNull() ?: return null
    return Expense(amount, parts[1], parts[2])
}

Now the most interesting part: loading a list of expenses via useLines, so the file is closed automatically and processing looks like working with a collection.

import java.io.File

fun loadExpenses(file: File): List<Expense> {
    if (!file.exists() || !file.isFile) return emptyList()

    return file.useLines { lines ->
        lines.mapNotNull { parseExpenseOrNull(it.trim()) }.toList()
    }
}

Notice the style: we return an already prepared List<Expense> to the outside. The file is closed immediately after the block, and that is exactly the behavior we need.

Writing the expense list via bufferedWriter().use { ... }:

import java.io.File

fun saveExpenses(file: File, items: List<Expense>) {
    file.parentFile?.mkdirs()

    file.bufferedWriter().use { w ->
        for (e in items) w.write(serializeExpense(e) + "\n")
    }
}

And a small main snippet showing that everything is connected (without complicating the command-line interface):

import java.io.File

fun main() {
    val storage = File("data/expenses.txt")
    val items = loadExpenses(storage)

    println("Loaded: ${items.size}") // Loaded: 0 (if the file doesn't exist yet)

    saveExpenses(storage, items + Expense(120, "food", "coffee"))
}

The “magic” here is not that we can store expenses (we could do that before in a list), but that the I/O code does not create a time bomb for you: the resource will always be closed, even if something crashes in the middle. That’s exactly what makes use such an important element of an adult style.

7. Typical mistakes when working with use {} and Reader/Writer

Mistake #1: open bufferedReader() and forget .use { ... }.
This most often happens when you’re “quickly checking an idea” and write val br = file.bufferedReader(), and then start reading. While the program is small, you don’t see the problem. Then an exception or an early exit appears, close() is not called, and weirdness begins: the file is “busy,” data “didn’t get written,” on Windows something “won’t let you delete the file.” It’s cured by habit: if you see bufferedReader()/bufferedWriter(), your hand automatically appends .use { ... }.

Mistake #2: try to return lines from useLines to the outside.
This is a logical trap: it seems like you returned “lines,” but in reality you returned a mechanism for reading from the file. And the file is closed immediately after the useLines block. The correct approach is to compute/filter/collect the result inside useLines and return an already prepared value, for example Int, String, or List<String>.

Mistake #3: put a lot of business logic inside the use block.
use should be a “narrow contact point with the resource”: read/write—and exit. If inside the block you start updating a bunch of structures, parsing commands, building reports, and also printing to the console, then during debugging you lose the simple rule: “inside use—only I/O.” The code becomes sticky and harder to test.

Mistake #4: forget about "\n" when writing via write().
After appendText() many people get used to “it’ll somehow do it.” But writer.write() writes exactly what you gave it. If you forgot "\n", the lines will “stick together” into one, and then your parser will honestly say: “parts are not 3, but 1”—and it will be right. So for line-by-line writing, either add "\n" by hand, or use a format convention (for example, “each entity is a separate line”).

Mistake #5: confuse “close the resource” and “handle the error.”
use guarantees closing the resource. But it does not turn failures into success and does not automatically “swallow” exceptions. If the file doesn’t exist or you don’t have permissions, you’ll get an exception where you perform I/O. So keep the separation of responsibilities in mind: use is responsible for closing, while handling I/O errors is a separate topic and a separate design (and you already know the basics via try/catch, but don’t mix everything into one pile).

1
Task
Kotlin SELF, level 42, lesson 4
Locked
Courier's Message
Courier's Message
1
Task
Kotlin SELF, level 42, lesson 4
Locked
Title from noise
Title from noise
1
Task
Kotlin SELF, level 42, lesson 4
Locked
Line counter
Line counter
1
Task
Kotlin SELF, level 42, lesson 4
Locked
Controller's report
Controller's report
1
Survey/quiz
Text files, level 42, lesson 4
Unavailable
Text files
Text files
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION