Best way to use BufferedReader in Kotlin
If you still wanted to read it line by line you could use some extension functions from std lib and do it as follows:
val reader = someStream.bufferedReader()
val iterator = reader.linesSequences().iterator()
while(iterator.hasNext()) {
val line = iterator.next()
// do something with line...
}
reader.close()
or alternatively, using a "functional" approach:
val reader = someStream.bufferedReader()
reader.useLines {
it.map { line -> // do something with line }
}
by using useLines, you don't need to explicitly call close on the reader, the useLines extensions function will do it for you!
Just adding those for reference.. cheers
you can also try using the "forEachLine" method.
val file = File("./folder/test.txt")
file.bufferedReader().forEachLine {
println("value = $it")
}
it'll also automatically close the stream after reading the last line
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-reader/index.html
fun Reader.forEachLine(action: (String) -> Unit)
Iterates through each line of this reader, calls action for each line read and closes the Reader when it's completed.
You can use bufferedReader
like so
val allText = inputStream.bufferedReader().use(BufferedReader::readText)