CodeGym /Courses /Kotlin SELF /Reading text: readText, readLines, forEachLine

Reading text: readText, readLines, forEachLine

Kotlin SELF
Level 42, Lesson 2
Available

1. Introduction

When people say “read a file”, beginners often imagine something like: “the program opened the file like Notepad and saw the letters”. In reality, a program always does a more boring (and honest) job: it takes the file and turns its contents into data inside your application — most often into a String or a List<String>.

With text files in Kotlin/JVM, what’s convenient is that the standard library and File provide ready-to-use methods “out of the box”, so we can choose a reading style for the task: read everything at once, read lines into memory, or process the file line by line using almost no memory.

It’s important to lock in one idea: by choosing a reading method, you are choosing a data shape. And the data shape strongly affects how easy it will be to write code next and how painful it will be for the computer (in memory and time).

How to choose a reading method

The choice between readText, readLines, forEachLine is not a question of “which method is correct”, but a question of “what data shape do I need next” and “how big is the file”.

So you don’t have to guess every time, it helps to keep a comparison in front of you.

Selection table

Method What it returns Memory When it’s convenient Typical “aftertaste code”
readText()
String
reads everything at once the file is “one meaningful string”: a template, a small text, a config string work: trim, split, replace, substring search
readLines()
List<String>
reads everything at once the file is logically made of lines, and you want collection operations map/filter/count/groupBy, sorting, line analysis
forEachLine {}
returns nothing directly (you accumulate the result yourself) line by line the file is large, or the result can be computed “on the fly” counters, search, max/min, accumulation into MutableList

There’s an important psychological point here: readText() and readLines() give you a ready result immediately, while forEachLine forces you to think “how will I accumulate the answer”. This is normal: line-by-line processing is almost always a bit more “algorithmic”.

Decision flowchart

Sometimes it’s easier to remember a small selection route rather than a table:

flowchart TD
    A[Need to read text from a file] --> B{Need the whole file as a single string?}
    B -->|Yes| C["readText()"]
    B -->|No| D{Need to have a list of lines in memory?}
    D -->|Yes| E["readLines()"]
    D -->|No, can process on the fly| F["forEachLine { ... }"]

If you catch yourself thinking “I’m uncomfortable with forEachLine, I want a list” — that’s an honest signal that you might really need readLines(). Just remember the cost: a list = memory.

A nuance about output performance

Sometimes you read a file in order to print many lines to the console. And here a classic trap appears: “I’ll do println for each line in a loop”. Technically it works, but with large volumes of output it can be slow. In the Kotlin community, it’s often recommended to build the output and print it with a single println using joinToString("\n") when there are many lines.

Today we’re not turning the lecture into an optimization race, but you can start cultivating the habit of “not printing a million println calls without a reason” right now.

2. readText() — when you need the whole file

Sometimes a file is just “one thing”: an email template, a small config, a saved report, a note text. In such cases, it’s most convenient to get it as a single string. For this, File has the readText() method.

After readText() you have a String, and you can do everything with the string that you already know how to do: length, trim(), split(), replace(), search for substrings, build reports via StringBuilder, and so on.

Minimal example of readText()

First, the smallest example to feel the mechanics:

import java.io.File

fun main() {
    val text: String = File("data/input.txt").readText()
    println("chars=${text.length}") // chars=...
}

If the file is small, this approach is almost always the most “brain-friendly”: one variable, one type, then pure string work.

Example: read → normalize → use

Often you want to “clean up” the text from a file first: remove extra whitespace at the edges, check that it’s not empty at all.

import java.io.File

fun main() {
    val raw = File("data/title.txt").readText()
    val title = raw.trim()

    println("title='$title'") // title='...'
}

Note: trim() here is not “cosmetics”, but real protection against surprises like “there was accidentally a newline at the end of the file”.

When readText() is a bad idea

readText() reads the entire file into memory as one string. If the file is large (for example, a log of hundreds of megabytes), you first spend memory on a huge String, and then you also spend time on operations over that string. This is where you want line-by-line processing.

A simple life heuristic: if you can open the file in Notepad and it doesn’t make Notepad contemplate the meaning of life — readText() is usually fine. If Notepad freezes and you have time to make tea — better not.

3. readLines() — when you need a list of lines

Next typical situation: the file is a set of lines, and each line means something. For example, a shopping list, a list of commands, a list of notes, a list of expenses. In such tasks it’s convenient to immediately get a List<String>, where each element is a separate line of the file. For this, there is readLines().

readLines() is good because it turns a file into a familiar collection, and with collections we already know how to do a lot: map, filter, count, firstOrNull, sortedBy, groupings, and so on.

Minimal example of readLines()

import java.io.File

fun main() {
    val lines: List<String> = File("data/input.txt").readLines()
    println("lines=${lines.size}") // lines=...
}

Now you don’t have a “hazy string with newlines”, but concrete list elements. This often makes code simpler and more readable.

Example: find the first non-empty line

A very typical scenario: the file may contain empty lines, and the first “useful” line matters to us.

import java.io.File

fun main() {
    val firstNonBlank = File("data/input.txt")
        .readLines()
        .firstOrNull { it.isNotBlank() }

    println(firstNonBlank) // for example: Hello
}

An important habit here: we use firstOrNull, not first. Because the file may turn out to be empty, and then first() will throw you an “exception party”.

Example: reading expenses from a text file

Let’s imagine that by this point in the course we already have an expense model (it appeared when we moved on to classes and data class). We’re not discussing “ideal formats” yet; we’ll take a simple line format:

amount|category|comment

For example:

350|food|coffee
1200|transport|metro card

Then reading into memory via readLines() looks natural: we want to get a list of lines, and then parse each line into an object.

import java.io.File

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

fun parseExpenseOrNull(line: String): Expense? {
    val parts = line.split("|")
    val amount = parts.getOrNull(0)?.toIntOrNull() ?: return null
    val category = parts.getOrNull(1)?.trim().orEmpty()
    val comment = parts.getOrNull(2)?.trim().orEmpty()
    return Expense(amount, category, comment)
}

Now we read the file and convert lines into expenses:

import java.io.File

fun main() {
    val lines = File("data/expenses.txt").readLines()
    val expenses = lines.mapNotNull { parseExpenseOrNull(it) }

    println("loaded=${expenses.size}") // loaded=...
}

Why is readLines() convenient here? Because we want a collection and we want to apply a “collection style” (mapNotNull) instead of manual loops and temporary variables.

Limitation of readLines()

Just like readText(), readLines() reads the file all at once, only not into a single string but into a list of lines. So in terms of memory it’s still “load everything at once”. For small and medium files, great. For very large ones, it’s better to switch to line-by-line processing.

4. forEachLine { ... } — line-by-line processing

Sometimes we don’t need to keep the whole file. We want to go through it and count, find, filter, but without creating a huge list of lines. For this, File has the line-by-line method forEachLine { line -> ... }. The idea is simple: Kotlin reads the file line by line and passes each line to your lambda.

This approach is often used for tasks similar to processing logs or large input data. In Kotlin materials it’s mentioned as a convenient tool specifically for line-by-line file reading.

Minimal example of forEachLine

import java.io.File

fun main() {
    var nonBlank = 0

    File("data/input.txt").forEachLine { line ->
        if (line.isNotBlank()) nonBlank++
    }

    println("nonBlankLines=$nonBlank") // nonBlankLines=...
}

Notice: we didn’t create a List<String>. We simply walked through the file and counted.

Example: find the maximum expense amount without storing lines

If the expenses file can be large, and we need, for example, the maximum by amount, then forEachLine fits well:

import java.io.File

fun main() {
    var maxAmount = 0

    File("data/expenses.txt").forEachLine { line ->
        val expense = parseExpenseOrNull(line) ?: return@forEachLine
        if (expense.amount > maxAmount) maxAmount = expense.amount
    }

    println("maxAmount=$maxAmount") // maxAmount=...
}

Here return@forEachLine appeared. This is not a “return from main”, but “skip the current line”. We do this if the line is broken or empty.

Why forEachLine is often safer for memory

forEachLine lets you work with a file like a “tape”: a line arrives → you process it → move on. Memory doesn’t bloat from a list of lines. This is especially nice when you don’t know in advance how big a file you’ll be handed (life loves sudden surprises).

5. Mini-assembly: read a file and prepare data for the application

Now we’ll build a neat “skeleton” for reading for our console application (conditionally, an expense tracker), but in a way that stays simple and doesn’t step into topics of the next lecture (writing) and the next days (reliable I/O).

The idea: we want one function that takes a File and returns a list of valid expenses. That’s it. No magic.

Reading function via readLines()

import java.io.File

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

    return file.readLines()
        .mapNotNull { line -> parseExpenseOrNull(line.trim()) }
}

This reads almost like plain English: “if the file doesn’t exist — empty; otherwise read lines and parse”.

Alternative via forEachLine

import java.io.File

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

    val result = mutableListOf<Expense>()
    file.forEachLine { line ->
        val e = parseExpenseOrNull(line.trim()) ?: return@forEachLine
        result.add(e)
    }
    return result
}

Yes, there’s a bit more code. But it doesn’t require holding a List<String> of all lines. We neatly accumulate only the “good” records.

6. Common mistakes when reading text from files

Mistake #1: choose readText() “out of habit”, then be surprised that the program eats memory.
readText() is a great method, but it literally means “read EVERYTHING”. If the file suddenly turns out to be large, you’ll get a huge String, and then heavy operations on it. In such cases, it’s useful to switch to readLines() or forEachLine() and think in lines.

Mistake #2: confuse “a line in a file” with “a string as a whole String”.
After readText() you have one big string, inside which there is "\n". Beginners sometimes expect that “since there are many lines in the file, the variable will be line-based somehow”. It won’t. If you need to work with lines, it’s faster (and clearer) to use readLines() right away.

Mistake #3: not normalizing lines before parsing.
Even a “clean” file often has trailing spaces, empty lines, extra newlines. If you do split("|") right away without trim() and without checking isBlank(), you’ll get weird bugs that look like “it worked yesterday, today it doesn’t”. Minimal protection is line.trim() and careful toIntOrNull().

Mistake #4: forget that the file may be missing, and the path may point to a directory.
If you immediately do File("...").readLines(), and the file isn’t found, the program will crash with an exception. We already know the basic checks exists() and isFile — and this is exactly the case where they really save nerves. Especially in learning projects, where directories and files move around all the time.

Mistake #5: try to “return a value” from forEachLine with a normal return.
Inside a forEachLine lambda, a normal return may behave not the way a beginner expects (rules for returns from lambdas matter). If you want to skip a line — use return@forEachLine. If you want to accumulate a result — create a variable outside and update it inside the lambda.

Mistake #6: mix reading and complex business logic in one huge block.
When inside forEachLine or right after readLines() you immediately start a “sheet” of conditions, counts, and report formatting, the code becomes hard to read and hard to debug. It’s much calmer to keep the style: “read → get a data structure → then process”, even if the data structure is still simple for now.

1
Task
Kotlin SELF, level 42, lesson 2
Locked
Analyst's note
Analyst's note
1
Task
Kotlin SELF, level 42, lesson 2
Locked
Clean list
Clean list
1
Task
Kotlin SELF, level 42, lesson 2
Locked
Sensor temperatures
Sensor temperatures
1
Task
Kotlin SELF, level 42, lesson 2
Locked
Error Hunt
Error Hunt
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION