Read All Lines of BufferedReader in Scala into a String

Kevin Meredith picture Kevin Meredith · Sep 20, 2013 · Viewed 12.9k times · Source

How can I read all of a BufferedReader's lines and store into a String?

 val br = new BufferedReader(...)
 val str: String = getAllLines(br) // getAllLines() -- is where I need help

Similar to this question.

Answer

joescii picture joescii · Sep 20, 2013

This is how I deal with a BufferedReader in Scala:

val br:BufferedReader = ???
val strs = Stream.continually(br.readLine()).takeWhile(_ != null)

You will have a string for each line from the reader. If you want it in one single string:

val str = Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\n")