This is my code:
try {
RandomAccessFile srcFile = new RandomAccessFile("src.txt", "rw");
} catch(FileNotFoundException e) {
e.printStackTrace();
}
This code gives me a warning that the RandomAccessFile
object srcFile is never closed.
But if I modify my code and declare the srcFile outside the try block (as in the code below), the warning goes away.
RandomAccessFile srcFile;
try {
srcFile = new RandomAccessFile("src.txt", "rw");
} catch(FileNotFoundException e) {
e.printStackTrace();
}
Why does this happen, since I'm not doing srcFile.close();
in any case?
Extract from this:
If a resource is stored in a field, no single method is considered as responsible for closing; no problem is reported.
I assume this is what is happening when declaring srcFile
outside of the scope of the try
. This implies that eclipse compiler cannot assume that the resource needs to be closed, because I may still be referenced outside of the scope in was created in.
Since JDK 1.7 you can solve this with try-with-resources:
try (RandomAccessFile srcFile = new RandomAccessFile("src.txt", "rw")) {
//Do something with srcFile
} catch(IOException e) {
e.printStackTrace();
}
Note that srcFile
will be closed automatically after the try has been executed.