I use the following style to read a file with BufferedReader
try (BufferedReader br = new BufferedReader(new FileReader("my_file"))) {
...
br.close();
} catch( IOException e ) {
System.out.println( e.getMessage() );
}
Things that I want to know:
1- Is close() in the right place?
2- Should I put another try..catch for `close()?
3- Since I used new for br, is the enough to call the close() or I have to write br = null for the GC?
4- FileReader has been newed, so should I destroy it?
close() would have been in the wrong place. To make sure your resource is always closed, you need to call close() in the finally blockYou are using try-with-resources statement in you code. In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly. You can learn more about this statement from documentation. So, here is modified version:
try (BufferedReader br = new BufferedReader(new FileReader("my_file"))) {
// your logic
} catch (IOException e) {
System.out.println(e.getMessage());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With