I was getting an warning on resource leak (BufferedReader was not closed). I fixed that by putting a close statement before the Return statement and ran the program. But I got an NullPointerException. My question is can it be closed automatically (somehow) when file reading was done. This question looks similar though.
Asked
Active
Viewed 2,225 times
4
-
`IOUtils.closeQuietly()` inside a `finally` – Stewart Feb 03 '14 at 13:22
-
1http://stackoverflow.com/questions/17739362/java7-try-with-resources-statement-advantage – assylias Feb 03 '14 at 13:23
-
I fixed my code but just curious to know if a resource can get closed automatically somehow. – Saikat Feb 03 '14 at 13:23
2 Answers
9
You can use try-with-resources Java 7 feature:
try(BufferedReader rdr = new BufferedReader(...)) {
...
}
it will be closed automatically when exiting block
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Evgeniy Dorofeev
- 133,369
- 30
- 199
- 275
2
Prior java 7 the general pattern of closable IO resources was like the following:
Resource r = null; // either stream, reader, writer etc
try {
r = ... // create resource
use resource r
} catch(IOException e) {
// some code
} finally {
if (r != null) {
r.close();
}
}
The resource is used in finally
block that guarantees that it will be closed whether the operation is done successfully or failed. null
-check is needed to prevent NPE if IOException
was thrown while creating the resource.
Java 7 introduced new syntax that creates illusion that the resource is closed "automatically":
try (
Resource r = // create resource
){
use resource r
} catch(IOException e) {
// some code
}
finally
block is actually added here automatically by compiler.
I hope this answers your question about automatic closing of BufferedReader
.

Anders R. Bystrup
- 15,729
- 10
- 59
- 55

AlexR
- 114,158
- 16
- 130
- 208