在 Scala 中将 InputStream 转换为 String 的惯用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5221524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Idiomatic way to convert an InputStream to a String in Scala
提问by bballant
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:
我有一个在 Java 中使用的方便的函数,用于将 InputStream 转换为 String。这是对 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?
在 Scala 中有没有一种惯用的方法来做到这一点?
回答by Rex Kerr
For Scala >= 2.11
对于 Scala >= 2.11
scala.io.Source.fromInputStream(is).mkString
For Scala < 2.11:
对于 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.
做几乎相同的事情。不过,不确定为什么要获得线条,然后将它们全部粘在一起。如果您可以假设流是非阻塞的,则可以使用.available
,将整个内容读入一个字节数组,然后直接从中创建一个字符串。
回答by raam
Source.fromInputStream(is).mkString("")
will also do the deed.....
Source.fromInputStream(is).mkString("")
也会做事.....
回答by Kamil Lelonek
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
}