Idiomatic way to convert an InputStream to a String in Scala

For Scala >= 2.11

scala.io.Source.fromInputStream(is).mkString

For Scala < 2.11:

scala.io.Source.fromInputStream(is).getLines().mkString("\n")

does pretty much the same thing. Not sure why you want to get lines and then glue them all back together, though. If you can assume the stream’s nonblocking, you could just use .available, read the whole thing into a byte array, and create a string from that directly.

Leave a Comment