Lesson contents

Kotlin — Reading files safely with useLines

In Kotlin, useLines provides a sequence of lines while a reader is open. Consume the sequence inside its block so the file can close as soon as the calculation finishes.

A simple example

Read back one letter

  1. Start with A
  2. Do this Write, then read
  3. Result A
A file stores the letter between the write and the read.
Lesson.kt
import java.nio.file.Files

fun main() {
    val file = Files.createTempFile("letter", ".txt")
    try {
        Files.writeString(file, "A")
        println(Files.readString(file))
    } finally {
        Files.delete(file)
    }
}
Output
A
Advertisements

Sum two lines from a temporary report

useLines closes the reader after the lambda finishes. Consume the lazy sequence inside that lambda. The outer finally removes the temporary path even if parsing fails.

Morning returns: 4. Afternoon returns: 7. End of day: 11.
Read a two-line count sheet

Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.

Run the example

Kotlin/JVM. Run these commands from the directory containing the example.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Lesson.kt
import java.nio.file.Files

fun main() {
    val path = Files.createTempFile("readings", ".txt")
    try {
        Files.write(path, listOf("4", "7"))
        val total = path.toFile().useLines { lines ->
            lines.filter { it.isNotBlank() }.sumOf { it.trim().toInt() }
        }
        println(total)
    } finally {
        Files.deleteIfExists(path)
    }
}
Output
11

The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.

Try it yourself

Add a third line containing 12.

Check your answer

The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.

Kotlin language documentation

Related tags

  • Kotlin
  • files
  • streams
  • resource management