Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader proper usage

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?

like image 286
mahmood Avatar asked May 17 '26 18:05

mahmood


2 Answers

  1. Since you use the try-with-resource statement, you don't need to close the stream explicitely. It is automatically closed in any case. If you wouldn't have used try-with-resource, the close() would have been in the wrong place. To make sure your resource is always closed, you need to call close() in the finally block
  2. If you call close() in the finally block, you need to catch the checked Exception thrown by it, too. If you use try-with-resource (like you did), you are fine
  3. All your variables live only in the scope of the try block, so you are safe
  4. BufferedReader closes the decorated Reader, so you don't have to close it explicitely
like image 78
Michael A. Schaffrath Avatar answered May 20 '26 08:05

Michael A. Schaffrath


You 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());
} 
like image 25
Ibrokhim Kholmatov Avatar answered May 20 '26 08:05

Ibrokhim Kholmatov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!