gpt4 book ai didi

scala - 在 Scala 中读取文件 : Stream closed

转载 作者:行者123 更新时间:2023-12-04 16:11:22 25 4
gpt4 key购买 nike

我尝试像这样在 Scala 中读取文件:

def parseFile(filename: String) = {
val source = scala.io.Source.fromFile(filename)
try {
val lines = source.getLines().map(line => line.trim.toDouble)
return lines
} catch {
// re-throw exception, but make source source is closed
case
t: Throwable => {
println("error during parsing of file")
throw t
}
} finally {
source.close()
}
}

当我稍后访问结果时,我得到一个

java.io.IOException: Stream Closed

我知道这是因为 source.getLines()只返回一个(懒惰的)Iterator[String] ,我已经关闭了 BufferedSourcefinally条款。

如何避免此错误,即如何在关闭源之前“评估”流?

编辑:我试着调用 source.getLines().toSeq这没有帮助。

最佳答案

也许,您可以尝试以下解决方案,它使代码更实用,并利用惰性求值。

首先,定义一个辅助函数using,它负责打开/关闭文件。

def using[A <: {def close() : Unit}, B](param: A)(f: A => B): B =
try f(param) finally param.close()

然后,您可以用函数式编程风格重构您的代码:

using(Source.fromFile(filename)) {
source =>
val lines = Try(source.getLines().map(line => line.trim.toDouble))
val result = lines.flatMap(l => Try(processOrDoWhatYouWantForLines(l)))
result.get
}

实际上,using函数可以用来处理所有需要在操作结束时关闭的资源。

关于scala - 在 Scala 中读取文件 : Stream closed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40460338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com