Using try-with-resource statement working with BufferedReader in Java

Working with BufferedReader and it's variants in Java was always a bit of a pain: developers need to not to forget close it and do the IOException handing doing it, not to mention about bunch of null-checks. Otherwise you program work could be interrupted with the most surprising and unpleasant way possible.
Prior the Java 7 we had to do smth. like this:

String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}

Despite the null check the attempt to close the reader in finally still could throw an IOException so developers has to 1) close the reader and 2) handle possible error.

In Java 7 BufferedReader implements java.lang.AutoCloseable , so we are no longer forced to close it manually, but IOException still can be thrown, like this:

String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
}
}

And finally Java 8 came along with all of it's might sugar. Now we have "try-with-resources" statement to help lazy developers and cover some resources access with the try/catch smart way and behind the scene. Code, using the Java 8 ability, would look like:

String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}

As you can see no try and no close() calls longer needed. Function throws IOException only because readLine() is called, if the internal logic of a function doesn't need it - this function wouldn't throw an error only because of buffered reader would close.

Tags: