【问题标题】:Read All Lines of BufferedReader in Scala into a String将Scala中BufferedReader的所有行读入字符串
【发布时间】:2013-09-26 06:15:14
【问题描述】:

如何读取BufferedReader所有行并将其存储到字符串中?

 val br = new BufferedReader(...)
 val str: String = getAllLines(br) // getAllLines() -- is where I need help

类似于这个question

【问题讨论】:

  • 一定要用BufferedReader吗?为什么不用Source.fromFile("myfile.txt").getLines() 或类似的?
  • 我需要使用BufferedReader,因为我从这里使用UnicodeBOMInputStream - stackoverflow.com/questions/1835430/…
  • 那么Source.fromInputStream(myUnicodeBOMInputStream).getLines() 可能会更容易。

标签: scala bufferedreader


【解决方案1】:

这就是我在 Scala 中处理BufferedReader 的方式:

val br:BufferedReader = ???
val strs = Stream.continually(br.readLine()).takeWhile(_ != null)

阅读器的每一行都会有一个字符串。如果你想在一个字符串中:

val str = Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\n")

【讨论】:

  • continually 的使用非常棒。我还不知道。谢谢!
  • 我建议根据Java API docs 直接调用BufferedReader.close()。请确保在您使用数据后调用它,因为Stream 是懒惰的。例如,使用mkString("\n") 的建议将强制评估Streamforce 也是如此。但是如果您在val strs = ... 行之后调用close(),您将无法读取任何行。
  • 有没有办法避免在您的解决方案中使用null
  • @kfkhalili,一种方法是:val str = Stream.continually(reader.readLine()).takeWhile(Option(_).nonEmpty).mkString("\n")
猜你喜欢
  • 2011-07-27
  • 2018-06-16
  • 1970-01-01
  • 2013-01-16
  • 2013-03-23
  • 1970-01-01
  • 2015-05-12
  • 2013-01-08
  • 2019-12-06
相关资源
最近更新 更多