Skip to Content
Course content

96: Reading Files with kotlin.io Extensions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you're working on a real project, you'll quickly find that Kotlin's standard library handles file I/O much more elegantly than Java does. Instead of wrestling with BufferedReader and manual try-finally blocks to close streams, Kotlin gives us extension functions on the File class that make the code read almost like a sentence.

To show you how this works, let's build a simple log analyzer. Imagine we have a file called server.log and we want to count how many times the word "ERROR" appears, but only for logs that happened in the "AuthService" module.

The quick and dirty approach with readText()

My first instinct when dealing with small files is usually to just grab everything at once. Kotlin makes this trivial with readText(). Here is how I'd start:

import java.io.File

fun main() {
    val logFile = File("server.log")
    val content = logFile.readText()
    
    val errorCount = content.lines()
        .count { it.contains("ERROR") && it.contains("AuthService") }
        
    println("Found $errorCount auth errors.")
}

This is clean, right? It's concise and it works perfectly for a 10KB file. But here's where I usually trip up early in my career: I'm treating the file like a string in memory. If server.log grows to 2GB, this code will throw an OutOfMemoryError and crash the JVM before it even gets to the counting logic. We should never load an entire file into a single string unless we are absolutely certain of its maximum size.

Avoiding the List trap with readLines()

You might think, "Okay, I'll just use readLines() instead." That sounds safer because it gives us a list of strings. But readLines() still reads the entire file into memory to build that List<String>. It's a marginal improvement in some cases, but it still doesn't solve the core problem of memory exhaustion for huge files.

Streaming data with useLines()

The "professional" way to do this—and the way I handle it in production—is using useLines(). This is the real powerhouse of the kotlin.io extensions. It opens the file, provides a Sequence of lines, and most importantly, it automatically closes the file once the block is finished.

Let's rewrite our analyzer to be memory-efficient:

import java.io.File

fun main() {
    val logFile = File("server.log")
    
    // useLines returns the result of the lambda and closes the reader automatically
    val errorCount = logFile.useLines { lines -> 
        lines.count { line -> 
            line.contains("ERROR") && line.contains("AuthService") 
        }
    }
    
    println("Found $errorCount auth errors.")
}

Notice the difference here. By using a Sequence (which is what lines is inside the block), Kotlin reads the file line-by-line. It doesn't matter if the log file is 1MB or 100GB; the memory footprint remains constant because only one line is held in memory at a time. I always reach for useLines when the file size is unpredictable.

  • readText(): Great for small config files where you need the whole blob.
  • readLines(): Handy for small files where you specifically need a List to perform indexed access.
  • useLines(): The gold standard for logs or large datasets.



📋 Practical Task

Build a System Environment Variable Auditor

Create a program that reads a text file named env_vars.txt. Each line in the file contains an environment variable in the format KEY=VALUE (e.g., DATABASE_URL=postgres://localhost:5432).

Your task is to use useLines() to process this file and print only the keys that have a value longer than 20 characters. Your output should look like this:

Long value found for key: DATABASE_URL
Long value found for key: API_SECRET_KEY

Requirements:

  • Do not load the entire file into memory.
  • Ensure the file is closed properly using the appropriate Kotlin extension.
  • Handle the string splitting for each line to separate the key from the value.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.