How to find out which thread locks the file in Java?

I'm trying to delete a file previously used by another thread in my program

I can't delete the file, but I don't know how to determine which thread may be using the file

So how to find out which thread locks the file in Java?

Solution

I don't have a direct answer (I don't think there is one, which is at the operating system level (native), I don't really see the value of the answer (once you find out which thread it is, you still can't programmatically close the file, but I don't think you know that you usually can't delete the file when it is still open. This can happen when you don't explicitly call closeable #close() on InputStream, OutputStream, reader or writer

Basic presentation:

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
}

In other words, ensure that the code in the entire Java IO content closes the resource correctly after use The normal idiom will do this in the try with resources statement so that you can be sure that resources will be released anyway, even in the case of IOException For example

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

Do any implementation of autocolosable for any InputStream, reader and writer, and open it yourself (using the new keyword)

Technically, this does not need to be implemented in some implementations, such as bytearrayoutputstream, but for clarity, it is only necessary to follow the final approximate idiom to avoid misunderstanding and reconstruction errors

If you haven't used java 7 or later, please use the try finally idiom below

OutputStream output = null;
try {
    output = new FileOutputStream(file);
    // ...
} finally {
    if (output != null) try { output.close(); } catch (IOException logorIgnore) {}
}

Hopefully this will help determine the root cause of your particular problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>