https://grokonez.com/java/java-9/java-9-try-resources-improvement
Java 9 try-with-resources Improvement
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
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:
// BufferedReader is declared outside try() block BufferedReader br = new BufferedReader(new FileReader("C://readfile/input.txt"));
try (BufferedReader inBr = br) {
// …
}
} catch (IOException e) {
// …
}
https://grokonez.com/java/java-9/java-9-try-resources-improvement
Java 9 try-with-resources Improvement
#java #java9 #try-with-resources