在 Scala 中将输入流转换为字符串的惯用方法
我在 Java 中使用了一个方便的函数,用于将 InputStream 转换为字符串。这是 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 a idioma way to do this 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 Scala >= 2.11
对于 Scala <= 2.11 2.11:
做几乎相同的事情。不过,不知道为什么你想要得到线条然后将它们全部粘在一起。如果您可以假设流是非阻塞的,则可以使用
.available
,将整个内容读入字节数组,然后直接从中创建一个字符串。For Scala >= 2.11
For Scala < 2.11:
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("")
也会做事......
Source.fromInputStream(is).mkString("")
will also do the deed.....
更快的方法来做到这一点:
Faster way to do this: