我正在处理 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 持有文件锁的其他原因是什么?我怎样才能知道,我怎样才能释放它们?
干杯,埃里克