在 Scala 中将输入流转换为字符串的惯用方法

发布于 2024-10-20 19:53:32 字数 520 浏览 2 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

海的爱人是光 2024-10-27 19:53:32

对于 Scala >= 2.11

scala.io.Source.fromInputStream(is).mkString

对于 Scala <= 2.11 2.11:

scala.io.Source.fromInputStream(is).getLines().mkString("\n")

做几乎相同的事情。不过,不知道为什么你想要得到线条然后将它们全部粘在一起。如果您可以假设流是非阻塞的,则可以使用 .available,将整个内容读入字节数组,然后直接从中创建一个字符串。

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.

我乃一代侩神 2024-10-27 19:53:32

Source.fromInputStream(is).mkString("")
也会做事......

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

Hello爱情风 2024-10-27 19:53:32

更快的方法来做到这一点:

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

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
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文