如何在Scala中逐行读取文件并在读取完毕后关闭文件?

5
通常,他们会告诉你要
import scala.io.Source
for(line <- Source.fromPath("myfile.txt").getLines())
  println(line)

这似乎是让文件保持打开状态。有没有可关闭的对应方法?

1个回答

22

您可以关闭 源代码 这样会关闭您的文件。

import scala.io.Source

val source = Source.fromFile("myfile.txt")
for (line <- source.getLines())
   println(line)
source.close()

谢谢,这个答案 让我分心了。我一直在想,为什么你们都使用 fromPath 而不是 fromFile?我的编译器说 fromPath is not a member of Source,我必须使用 fromFile。 - Valentin Tihomirov
你也可以引起注意,使用这种方法。链接 - Valentin Tihomirov
你们为什么都用fromPath而不是fromFile?你也是其中的一员。说实话,我只是从你的问题中复制了这个。实际上并没有这样的方法。我修正了我的答案,使用了fromFile - Łukasz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接