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

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

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

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

解决方法

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

基本演示:

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
}

换句话说,确保在整个Java IO内容代码在使用后正确关闭资源. The normal idiom将在the try-with-resources statement中执行此操作,以便您可以确定无论如何都将释放资源,即使在IOException的情况下也是如此.例如.

try (OutputStream output = new FileOutputStream(file)) {
    // ...
}

为任何InputStream,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) {}
}

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

相关文章

应用场景 C端用户提交工单、工单创建完成之后、会发布一条工...
线程类,设置有一个公共资源 package cn.org.chris.concurre...
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量