Search code examples
scalabufferedreader

Read All Lines of BufferedReader in Scala into a String


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.


Solution

  • 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")