Read File Content as List of Lines in Kotlin
To read file content as List of lines, use File.readLines() method.
In this tutorial, we will learn how to read file content as a list of lines in Kotlin.
The function used to read the lines from a text file is
Method | Description |
---|---|
File.readLines() | Reads file content as a list of lines |
Example 1 – Read Lines in Text file as List
In this example, we will read a text file, “file.txt”, present at the root of the project. We will use File.readLines() method.
file.txt
Hello World.
Welcome to Kotlin Tutorial by www.tutorialkart.com.
Learning Kotlin is easy.
example.kt
</>
Copy
import java.io.File
/**
* Kotlin Example to read contents of file line by line
*/
fun main(args: Array) {
val fileName :String = "file.txt"
var i :Int = 1
// using extension function readLines
File(fileName).readLines().forEach {
print((i++))
println(": "+it)
}
}
Output
1: Hello World.
2: Welcome to Kotlin Tutorial by www.tutorialkart.com.
3: Learning Kotlin is easy.
Conclusion
In this Kotlin Tutorial – Kotlin Read File to Lines, we have learnt to read content of file line by line. In our next tutorial, we shall learn to write data to file.