Reputation: 24705
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 new
ed, so should I destroy it?
Upvotes: 3
Views: 1526
Reputation: 2110
close()
would have been in the wrong place. To make sure your resource is always closed, you need to call close() in the finally
blockUpvotes: 5
Reputation: 7123
you are using try-with-resources statement. You don't need to explicitly call close on your Reader. Indeed the documentation state:
The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
Furthermore your FileReader is Decorated by the BufferedReader and closing BufferedReader should close the FileReader.
Upvotes: 1
Reputation: 1089
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());
}
Upvotes: 2
Reputation: 1335
1-2- It is better to use close together with a finally or resource block. Otherwise the close will not get called if an Exception occurs before.
3- It is enough to call close(). Setting objects to null does not delete the reference. GC will destroy the objects when there are nor references to the objects anymore. So don't destroy your objects manually.
Upvotes: 0