Idiomatic way to convert an InputStream to a String in Scala

StringScalaInputstream

String Problem Overview


I have a handy function that I've used in Java for converting an InputStream to a String. Here is a direct translation to Scala:

  def inputStreamToString(is: InputStream) = {
    val rd: BufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8")) 
    val builder = new StringBuilder()    
    try {
      var line = rd.readLine 
      while (line != null) { 
        builder.append(line + "\n")
        line = rd.readLine
      }
    } finally {
      rd.close
    }
    builder.toString
  }

Is there an idiomatic way to do this in scala?

String Solutions


Solution 1 - String

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.

Solution 2 - String

Source.fromInputStream(is).mkString("") will also do the deed.....

Solution 3 - String

Faster way to do this:

	private def inputStreamToString(is: InputStream) = {
	    val inputStreamReader = new InputStreamReader(is)
	    val bufferedReader = new BufferedReader(inputStreamReader)
	    Iterator continually bufferedReader.readLine takeWhile (_ != null) mkString
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbballantView Question on Stackoverflow
Solution 1 - StringRex KerrView Answer on Stackoverflow
Solution 2 - StringraamView Answer on Stackoverflow
Solution 3 - StringKamil LelonekView Answer on Stackoverflow