Java 7 introduces a new approach for closing resources by try-with-resources statement. After that, Java 9 try-with-resources makes an improved way of writing code. Now we can simplify our code and keep it cleaner and clearer.
Related post: Java 7 – try-with-resources Statement
1. Java 7 try-with-resources
This is the way we use it from Java 7:
1 2 3 4 5 6 7 8 9 |
try (BufferedReader br = new BufferedReader(new FileReader("C://readfile/input.txt"))) { String line; while (null != (line = br.readLine())) { // processing each line of file System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } |
It is good, but we have to declare the variable in try()
block.
That’s because we can’t use resource which is declared outside the try()
block within it. If resource is already declared outside, we should re-refer it with local variable:
1 2 3 4 5 6 7 8 9 |
// BufferedReader is declared outside try() block BufferedReader br = new BufferedReader(new FileReader("C://readfile/input.txt")); try (BufferedReader inBr = br) { // ... } } catch (IOException e) { // ... } |
2. Java 9 try-with-resources improvement
Java 9 make things simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// BufferedReader is declared outside try() block BufferedReader br = new BufferedReader(new FileReader("C://readfile/input.txt")); // Java 9 make it simple try (br) { String line; while (null != (line = br.readLine())) { // processing each line of file System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } |
But we should notice that the br
variable should be effectively final or declared final.
An effectively final variable is the variable that never changed after initializing. That means the compiler finds it never appear in assignments outside its initialization.
Last updated on September 11, 2018.