【问题标题】:Do Scala files need to be released before deleting?Scala文件是否需要在删除前释放?
【发布时间】:2011-12-23 03:43:28
【问题描述】:

在下面的代码中,如果我取消注释 for 循环,则文件不再被删除

val file = "myfile.csv"
//for (line <- Source.fromFile(file).getLines()) { }
new File(file).delete()

如果是这样,我应该调用某种类型的关闭函数吗?

【问题讨论】:

  • Windows 在打开文件时锁定文件,防止其他操作,如删除。你是对的,你确实需要明确关闭文件。

标签: scala


【解决方案1】:

您应该调用某种关闭方式:

val file = "myfile.csv"
val source = Source.fromFile(file)
for (line <- source.getLines()) { }
source.close
new File(file).delete

但这有点乏味。如果将 for 循环重写为

source.getLines().foreach{ line => }

你可以

class CloseAfter[A <: { def close(): Unit }](a: A) {
  def closed[B](f: A => B) = try { f(a) } finally { a.close }
}
implicit def close_things[A <: { def close(): Unit }](a: A) = new CloseAfter(a)

现在你的代码会变成

val file = "myfile.csv"
Source.fromFile(file).closed(_.foreach{ line => })
new File(file).delete

(如果您在代码中多次执行此操作,或者您已经维护了自己的有用函数库,并且很容易在此处添加关闭隐式以便您可以使用它,这将是一个好处无处不在)。

【讨论】:

    【解决方案2】:

    正如其他人所说,是的,您需要在完成后关闭Source。另一个好的解决方案是使用scala-arm 自动为您关闭文件。

    import resource._
    
    val file = "myfile.csv"
    for {
      source <- managed(Source.fromFile(file))
      line <- source.getLines()
    } {
    }
    new File(file).delete
    

    【讨论】:

      【解决方案3】:

      读完“Why doesn't Scala Source close the underlying InputStream?”后,改用“scala-incubator / scala-io”。

      它在a Path 上包含一个delete operation,它负责处理所有事情。该库始终确保在每次使用后安全关闭文件。

      【讨论】:

        猜你喜欢
        • 2011-05-03
        • 2019-04-21
        • 1970-01-01
        • 2011-08-27
        • 2018-11-10
        • 1970-01-01
        • 2018-08-07
        • 2012-07-17
        • 2021-11-10
        相关资源
        最近更新 更多