Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
96: Reading Files with kotlin.io Extensions
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
Listto 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.
There are no comments for now.