[英]Where is the JVM holding my file lock?
我正在处理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还会持有文件锁的其他原因是什么? 我如何找到它们,如何释放它们?
干杯,埃里克
我只知道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(())
要么:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.