Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use BufferedReader in Kotlin

So I've just started using Kotlin for Android, and converted my Android Java codes into Kotlin.

In one of the conversions, I stumbled upon a BufferedReader, which I would usually write in Java as the following:

String result = ""; String line = ""; BufferedReader reader = new BufferedReader(someStream); while ( (line = reader.readLine()) != null ) {     result += line; } 

But in Kotlin, it seems that Kotlin doesn't allow me to assign values to variables in while conditions.

Currently, I've written the code as the following:

val reader = BufferedReader(someStream) var line : String? = "" while (line != null) {     line = reader.readLine()     result += line } 

which I don't find so elegant and feels prev-gen, despite using Kotlin.

What would be the best way to use BufferedReader in Kotlin?

like image 202
Akira Kido Avatar asked Dec 06 '16 16:12

Akira Kido


People also ask

What is BufferedReader in Kotlin?

A buffered character-input stream that keeps track of line numbers. Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

How do I read the contents of a kotlin file?

1) Select "Project" from the top of the vertical toolbar to open the project "tool window" 2) From the drop-down menu at the top of the "tool window", select "Android" 3) Right-click on "App" and select "New" then -> "Folder" (the one with the green Android icon beside it) then -> "Assets Folder" 4) Right-click on the ...


2 Answers

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

like image 29
João Gonçalves Avatar answered Oct 01 '22 02:10

João Gonçalves


You can use bufferedReader like so

val allText = inputStream.bufferedReader().use(BufferedReader::readText) 
like image 83
miensol Avatar answered Oct 01 '22 00:10

miensol