Question

Apparently I am always calling FileReader#close() and FileWriter#close(), but some of my files remained locked by my own code.

How to

1) close file fully?

2) check, where in the code it was opened and not closed?

Was it helpful?

Solution

The question is vague and is missing context, so it makes it difficult to answer and encourages assumptions, never a good place to start from...

However, if you are doing something similar to...

try {
    FileReader fr = new FileReader(new File("..."));
    // Read file...
    fr.close();
} catch (IOException exp) {
    exp.printStackTrace();
}

Then if an exception occurs for some reason (or the code returns before it reaches the close statement), then close will never be called...

Prior to Java 7, one would typically do something like...

FileReader fr = nulll;
try {
    fr = new FileReader(new File("..."));
    // Read file...
} catch (IOException exp) {
    exp.printStackTrace();
} finally {
    try {
        // Avoid NullPointerException's
        if (fr != null) {
            fr.close();
        }
    } catch (Exception exp) {
    }
}

This ensures that regardless of what happens between the try-catch, finally will always be called and you can take steps to ensure that the resource is closed.

With Java 7, you can now take advantage of the "try-with-resources" feature...

try (FileReader fr = new FileReader(new File("..."))) {
    fr = ;
    // Read file...
} catch (IOException exp) {
    exp.printStackTrace();
}

Which is basically a short-cutted version of the try-catch-finally example block.

If you are using the FileLock functionality, then you also need to ensure that you releasing the FileLock when you are done with, in a similar fashion to the try-catch-finally example above, but file locking will only ensure that different processes can't read/write the simultaneously, it doesn't protect you against multiple threaded access...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top