Part 08 / Topic 3 of 7
Reading text: readText(), readLines(), forEachLine()
Three ways to read a file back, each suited to a different need.
val shoppingList = File("shopping.txt")
shoppingList.writeText("Rice\nDal\nAtta\nMilk\n")
// readText(): the whole file as one String, newlines and all
val wholeFile = shoppingList.readText()
println("readText() gives one String of length ${wholeFile.length}")
// readLines(): the whole file as a List<String>, one entry per line, no newline characters
val lines = shoppingList.readLines()
println("readLines() gives a List<String>: $lines")
println("Item 1 of ${lines.size}: ${lines[0]}")
// forEachLine: streams through the file one line at a time, without loading
// every line into memory as a List first -- the right choice for a genuinely large file
var lineNumber = 0
shoppingList.forEachLine { line ->
lineNumber++
println("Line $lineNumber: $line")
}
readText() gives one String of length 19
readLines() gives a List<String>: [Rice, Dal, Atta, Milk]
Item 1 of 4: Rice
Line 1: Rice
Line 2: Dal
Line 3: Atta
Line 4: Milk
Reach for readLines() when you need the whole thing as a list you can index, sort or filter
(it's genuinely in memory as a List<String>). Reach for forEachLine() when a file could be
large and you only need to process it line by line -- it never holds more than the current line
plus the buffer in memory. readText() is for the cases where the content really is "one blob
of text", like this part's diary example.
Full program: examples/03_reading_text.kt.
Done here? The practice set for Part 8 — including the solutions — is on the part page.