我需要使用 Source.getLines() 创建一个迭代器,并快速查看 Scala 源代码,运行一些测试后,迭代器似乎没有关闭 即使在迭代器耗尽之后(即,在 hasNext() 开始为 false 之后)。
我想知道 Scala 推荐的关闭/释放用于创建迭代器的资源的技术是什么。我发现 一个有趣的库,看起来它可以解决这个问题:
https://github.com/jsuereth/scala-arm
但是,我更喜欢使用核心 scala 库而不是 如果可能的话,引入第三方的东西。如果你感兴趣 在我如何测试这个(在 Linux 上使用“lsof”列出打开的文件)中,我的 代码如下:
object Test extends App {
import sys.process._
import scala.io.Source._
"echo hello world" #> new java.io.File("/tmp/testing") !
val src = fromFile("/tmp/testing")
val iter: Iterator[String] = src.getLines()
while (iter.hasNext) {
println("line=" + iter.next())
}
println("iterator exhausted.. sleeping while we check if file is still open using lsof")
Thread.sleep(200000)
}
运行程序后,它仍然处于 sleep 状态,运行以下命令:
lsof | grep /tmp/testing
你可能会看到这样的输出:
java 15813 ...253,0.... 12 .. lots-of-othernumbers..0462 /tmp/testing
然后,当程序终止时,grep 将显示为空(如您所想)。
预先感谢您提供的任何提示!
最佳答案
这是我倾向于使用的模式:
def using[R <: Closeable, T](stream: R)(f: R => T): T =
try {
f(stream)
} finally {
stream.close()
}
你可以这样使用:
def readSomeLines(is: InputStream) = {
using(new BufferedReader(new InputStreamReader(is))) { stream =>
Iterator.continually(stream.readLine().takeWhile(_ != null)).foreach(println)
}
}
readSomeLines(new FileInputStream("/tmp/foo"))
关于scala - 如何关闭由 Source.fromFile ("/tmp/foo").getLines() 返回的迭代器关联的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32599039/