The code here gives a warning that Resource leak: 'f' is never closed
.
if I close f inside the try block it works but it if I place f.close()
inside the finally block it doesn't work. It shows the error f cannot be resolved
. So what's the problem?
So the program is supposed to take input from the user and save it in a .doc file then read the data from the same file and print it out. I am learning Java if it's not already obvious.
So the code works but I noticed that there is a warning that f
isn't closed. I put the f.close()
statement in the finally
block. It shows an error there.
The close statement runs when it is in the try
block but can't recognize f
in the finally
block.
try {
RandomAccessFile f = new RandomAccessFile("E:\\emp.doc","r");
for (i = 0; i < size; i++) {
id1[i] = f.read();
name[i] = f.readUTF();
add[i] = f.readUTF();
sal[i]=f.readDouble();
if (sal[i] > 25000) {
System.out.println("ID:" + id1[i] + "\nName: " + name[i] +
"\nAddress:" + add[i] + "\nSalary" + sal[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}//finally {
// f.close();
//}
So in the code if I don't place the finally
block the program works but shows a warning that f
isn't closed.
If I try to put the close
inside the try
block then there is no warning.
But if I put the close
inside the finally
block then there is a error f cannot be resolved
.
So what do I have to do to address the warning?