Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close file in finally block doesn't work

try {
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line = null;
} catch (FileNotFoundException fnf) {
    fnf.printStackTrace();
} finally {
    fr.close();
}

The fr.close() shows an error:

fr cannot be resolved

I had read that closing a file in the finally block is a good practice.
What is that am doing wrong?

like image 225
noMAD Avatar asked Jan 24 '12 03:01

noMAD


People also ask

What happens if you don't close a file in Java?

If you write to a file without closing, the data won't make it to the target file. But after some surfing I got to know that Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

Why you need to close the stream in finally block?

This ensures that all the opened files are properly closed and all the running threads are properly terminated. So, the data in the files will not be corrupted and the user is on the safe-side.

Why do we need to close a file in Java?

In java API there is a interface Closeable Interface, those classes implement this interface they need to be close after use. It closes the stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.


1 Answers

The variable fr only has scope within the try block. It is out of scope in the finally block. You need to declare it before the try block:

FileReader fr = null;
try {
    fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line = null;
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (fr != null) {
        try {
            fr.close();
        } catch (IOException e) {
            // This is unrecoverable. Just report it and move on
            e.printStackTrace();
        }
    }
}

This is quite a common pattern of code, so it's good to remember it for future similar situations.

Consider throwing IOException from this method - printing track traces isn't very helpful to callers, and you wouldn't need the nested try catch around fr.close()

like image 109
Bohemian Avatar answered Oct 14 '22 04:10

Bohemian