如何找出哪个线程在java中锁定文件?

tom*_*dee 7 java multithreading file-locking

我正在尝试删除我的程序中的另一个线程之前使用过的文件.

我无法删除该文件,但我不知道如何确定哪个线程可能正在使用该文件.

那么如何找出哪个线程在java中锁定文件?

Bal*_*usC 7

我没有一个直接的答案(我不认为有一个,这是在操作系统级别(本机),而不是在JVM级别控制)我也没有真正看到答案的价值(一旦发现它是哪个线程,你仍然无法以编程方式关闭文件,但我认为你还不知道当文件仍处于打开状态时通常无法删除.当您没有明确地调用,或者围绕有问题构建Closeable#close()的时InputStream,可能会发生这种情况.OutputStreamReaderWriterFile

基本演示:

public static void main(String[] args) throws Exception {
    File file = new File("c:/test.txt"); // Precreate this test file first.
    FileOutputStream output = new FileOutputStream(file); // This opens the file!
    System.out.println(file.delete()); // false
    output.close(); // This explicitly closes the file!
    System.out.println(file.delete()); // true
}
Run Code Online (Sandbox Code Playgroud)

换句话说,确保在整个Java IO内容中代码在使用后正确 关闭资源.正常的成语是为此在该try-with-resources声明中,这样你可以肯定的是,资源总会被释放出来,甚至在的情况下IOException.例如

try (OutputStream output = new FileOutputStream(file)) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

做到这一点对任何 InputStream,OutputStream,Reader和Writer等任何工具AutoCloseable,这你打开自己(使用new关键字).

这在某些实现中在技术上是不需要的,例如ByteArrayOutputStream,但是为了清楚起见,只需遵守最终的近似成语,以避免误解和重构错误.

如果您还没有使用Java 7或更新版本,请使用以下try-finally习惯用法.

OutputStream output = null;
try {
    output = new FileOutputStream(file);
    // ...
} finally {
    if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
}
Run Code Online (Sandbox Code Playgroud)

希望这有助于确定您特定问题的根本原因.