1

我正在处理 java.nio.file.AccessDeniedException 问题。

我有一个 Scala 程序,如果我这样做:

java.nio.file.Files.delete(FileSystems.getDefault().getPath("""D:\Users\Eric\Google Drive (New)\Music\Downloaded\Foreigner [Discography HQ]\1977 - Foreigner\03 - Starrider.mp3""")) 

一切正常。我有一些我做的代码

def delete(path : Path) {
  try {
    println("deleting " + path)
    java.nio.file.Files.delete(path)
  } catch {
    case exception: Exception => System.err.println(exception)
  }
}

val google1 = FileSystems.getDefault().getPath("""D:\Users\Eric\Google Drive\Music\Downloaded\Foreigner [Discography HQ]""")
val google2 = FileSystems.getDefault().getPath("""D:\Users\Eric\Google Drive (New)\Music\Downloaded\Foreigner [Discography HQ]""")

val duplicates = TraversablePaths(List(google1, google2)).duplicateFilesList

println("deleting duplicate files")
duplicates.foreach(_.filter(!_.startsWith(google1)).foreach(delete))

但是当我尝试删除同一个文件时,我得到

java.nio.file.AccessDeniedException: D:\Users\Eric\Google Drive (New)\Music\Downloaded\Foreigner [Discography HQ]\1977 - Foreigner\03 - Starrider.mp3

我能说的最好的事情是 JVM 要么锁定文件,要么锁定文件所在的目录,但我不知道在哪里。检查文件是否相同的代码看起来像

def identical(file1 : Path, file2 : Path) : Boolean = {

  require(isRegularFile(file1), file1 + " is not a file")
  require(isRegularFile(file2), file2 + " is not a file")

  val size1 = size(file1)
  val size2 = size(file2)

  if (size1 != size2) return false

  var position : Long = 0
  var length = min(Integer.MAX_VALUE, size1 - position)

  val channel1 = FileChannel.open(file1)
  val channel2 = FileChannel.open(file2)

  try {
    while (length > 0) {
      val buffer1 = channel1.map(MapMode.READ_ONLY, position, length)
      val buffer2 = channel2.map(MapMode.READ_ONLY, position, length)
      if (!buffer1.equals(buffer2)) return false
        position += length
    length = min(Integer.MAX_VALUE, size1 - position)
    }
    true
    } finally {
    channel1.close()
    channel2.close()
  }
}

我原以为关闭通道会释放 JVM 需要的任何文件锁。这是我实际打开文件进行读取的代码的唯一部分,尽管代码的其他部分确实会检查文件长度,但我不希望 JVM 需要文件锁。

JVM 持有文件锁的其他原因是什么?我怎样才能知道,我怎样才能释放它们?

干杯,埃里克

4

1 回答 1

5

我只知道 JavaDoc 是怎么说的:

映射一旦建立,就不再依赖于用于创建它的文件通道。特别是关闭通道对映射的有效性没有影响。

映射的字节缓冲区和它所代表的文件映射在缓冲区本身被垃圾收集之前保持有效。

您可能没有保留缓冲区,但也可能没有被 GC 处理。

更新:稍后我将重新启动到 Windows 进行尝试,但这在 linux 上不会有问题。

更新:...但是在 Windows 上,是的,这就是问题所在。

package niolock

import java.nio.channels._
import java.nio.file._
import FileChannel.MapMode.{ READ_ONLY => RO }

import scala.util._

object Test extends App {
  val p = FileSystems.getDefault getPath "D:/tmp/mapped"
  val c = FileChannel open p
  var b = c map (RO, 0L, 100L)
  c.close

  Console println Try(Files delete p)
  b = null
  System.gc()
  Console println Try(Files delete p)
}

尝试一下:

$ scalac niolock.scala ; scala niolock.Test
Failure(java.nio.file.AccessDeniedException: D:\tmp\mapped)
Success(())

或者:

在 Windows 中释放 Java 文件锁

java - 如何从使用Java中的FileChannel映射的内存中取消映射文件?

于 2014-03-12T02:51:47.237 回答