Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to convert an InputStream to a String in Scala

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?

like image 991
bballant Avatar asked Mar 07 '11 15:03

bballant


People also ask

How do I change InputStream to String?

To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.

What is Bufferedsource in Scala?

A flexible iterator for transforming an Iterator[A] into an Iterator[Seq[A]], with configurable sequence size, step, and strategy for dealing with elements which don't fit evenly.


3 Answers

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.

like image 66
Rex Kerr Avatar answered Oct 05 '22 15:10

Rex Kerr


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

like image 24
raam Avatar answered Oct 05 '22 14:10

raam


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
    }
like image 45
Kamil Lelonek Avatar answered Oct 05 '22 14:10

Kamil Lelonek