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?
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.
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.
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.
Source.fromInputStream(is).mkString("")
will also do the deed.....
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With