【发布时间】:2017-03-20 12:15:32
【问题描述】:
我尝试像这样在 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],并且我已经关闭了finally 子句中的BufferedSource。
如何避免此错误,即如何在关闭源之前“评估”流?
编辑:我试图打电话给source.getLines().toSeq,但没有帮助。
【问题讨论】:
-
你可以返回一个列表而不是一个迭代器。只需
return lines.toList。 -
@marstran 我尝试了 toSeq,但它不起作用(运行时类型仍然是 Stream)。使用 toList,它可以工作,谢谢
标签: scala