27

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.

Community
  • 1
  • 1
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • 1
    Do you have to use `BufferedReader`? Why not `Source.fromFile("myfile.txt").getLines()` or similar? – yotommy Sep 20 '13 at 19:17
  • 1
    I need to use a `BufferedReader` since I'm making use of the `UnicodeBOMInputStream` from here - http://stackoverflow.com/questions/1835430/byte-order-mark-screws-up-file-reading-in-java. – Kevin Meredith Sep 20 '13 at 19:47
  • Then perhaps `Source.fromInputStream(myUnicodeBOMInputStream).getLines()` would be easier. – Shadowlands Sep 20 '13 at 23:09

1 Answers1

63

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")
joescii
  • 6,495
  • 1
  • 27
  • 32
  • 3
    The use of `continually` is brilliant. I didn't know it yet. Thanks! – Madoc Sep 23 '13 at 12:49
  • 2
    I recommend simply calling `BufferedReader.close()` per the [Java API docs](http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#close()). Just be sure to call it after you have consumed the data because `Stream` is lazy. The suggestion to use `mkString("\n")` will force the evaluation of the `Stream` for instance, as will `force`. But if you were to call `close()` after the `val strs = ...` line, you will not be able to read any lines. – joescii Oct 30 '15 at 17:06
  • 1
    Is there a way to avoid using `null` in your solution? – kfkhalili Feb 21 '20 at 16:31
  • @kfkhalili, one approach would be: `val str = Stream.continually(reader.readLine()).takeWhile(Option(_).nonEmpty).mkString("\n")` – Michael-7 Apr 03 '21 at 23:14