CodeBlanks Logo Icon CodeBlanks

readLines

Learn to read lines with File.readLines.

readLines: List of lines

readLines() reads the file line by line and returns each line as a String inside a List<String>. Line break characters (\n) are stripped. This makes it easy to process lines one by one.

val f = File("meyveler.txt")
f.writeText("apple\nbanana\ncherry")
val lines = f.readLines()
println(lines.size)   // 3
println(lines[0])     // apple

readLines loads all lines into memory; it suits small and medium files. For very large files prefer useLines for stream-based reading. The returned list is immutable; to modify it use toMutableList().

Looping over lines

You can loop over the list returned by readLines with a for loop to visit each line. This is a common pattern to process each line separately (for example numbering or filtering). Use forEachIndexed to also get the index.

val lines = f.readLines()
for ((i, line) in lines.withIndex()) {
    println("${i + 1}: $line")
}

Here each line is printed with its number in front. The withIndex() method turns the list into index-value pairs. This pattern is very useful when processing log files or reports.

Practice Read lines and print them

Create val f = File("meyveler.txt"). Write three lines with f.writeText("apple\nbanana\ncherry"). Read the lines with val lines = f.readLines(). Print the count with println(lines.size), then loop with for (line in lines) and println each line. Add the import java.io.File import.

Starter code

Main.kt
import java.io.File

// File object for path meyveler.txt
// write "apple\nbanana\ncherry" (three lines)
// read with readLines, print size then each line
fun main() {
    // write here
}

Sample solution

Main.kt
fun main() {
    val f = File("meyveler.txt")
    f.writeText("apple\nbanana\ncherry")
    val lines = f.readLines()
    println(lines.size)
    for (line in lines) println(line)
}

Expected output

3
apple
banana
cherry

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the readLines concepts

Term Meaning
readLines() Reads lines
List<String> Return type
lines.size Line count
lines[0] First line

2 Read the lines

Question
val lines = f.____()
Answer
val lines = f.readLines()

Explanation: readLines returns lines as a List<String>.

3 What type does readLines() return?

  • String
  • Array<Byte>
  • Map<String, Int>
  • List<String> Correct answer

Explanation: readLines returns a List<String> with each line as an element.

All lessons in Intermediate