Reading line by line using bufferedReader
In this recipe, we will understand how to use the bufferedReader to read the contents of a file line by line.
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need the Kotlin compiler installed along with JDK. You can also use IntelliJ IDEA for the development environment.
How to do it…
In the given steps, we will learn how to use BufferedReader to read a file line by line:
- Let's start with getting the
InputStreamof our file and use theBufferedReaderon it to read the contents of the file line by line:
import java.io.File
import java.io.InputStream
fun main(args: Array<String>) {
val listOfLines = mutableListOf<String>()
val inputStream: InputStream = File("lorem.txt").inputStream()
inputStream.bufferedReader().useLines {
lines -> lines.forEach {
var x = "# (" + it.length + ") " + it.substring...