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
- Start with A
- Do this Write, then read
- Result A
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)
}
}
A
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 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
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)
}
}
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.