Kotlin read file with File.useLines

File.useLines() reads all data as a list of lines and provides it to the callback. It closes the reader in the end.

Kotlin read a file with File.useLines

The example reads a file and prints it to the console. We add line numbers to the output.
import java.io.File
 
fun main(args: Array<String>) {
    
    val fileName = "src/resources/sample.txt"
    
    val myList = mutableListOf<String>()

    File(fileName).useLines { lines -> myList.addAll(lines) }
    
    myList.forEachIndexed { i, line -> println("${i}: " + line) }
}
A mutable list is created:
val myList = mutableListOf<String>()
With File.useLines() we copy the list of the lines into the above created mutable list:
File(fileName).useLines { lines -> myList.addAll(lines) }
With forEachIndexed() we add a line number to each line:
myList.forEachIndexed { i, line -> println("${i}: " + line) }


Comments