2

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 1
    Learn the basics of Java syntax - https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – Boris the Spider Jul 09 '19 at 07:37
  • 4
    that means that `f` is declared within your `try` block. Either move it to before the `try` block or use try-with-resources. – Scary Wombat Jul 09 '19 at 07:38
  • [try with resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) much safer all round – MadProgrammer Jul 09 '19 at 07:40

1 Answers1

2

Change it to

try ( RandomAccessFile f = new RandomAccessFile("E:\\emp.doc","r")){
....
}

Close is not needed as it will automatically get called once try-scope ends.

Kris
  • 8,680
  • 4
  • 39
  • 67
  • Learn more about the syntax and constructs for better understanding. You can accept this answer if it worked! – Kris Jul 09 '19 at 07:43
  • This is the correct way to do it. It's called a try-with-resources-statement. It automatically closes the resource `f` after the statement is done. This can be used with any object implementing `java.lang.AutoCloseable`. Most of the IO classes do that. You should add some explanation to your answer to give it more value to those learning the language. Other than that, yes, this is the best way. – bkis Jul 09 '19 at 08:13