Bạn có chắc chắn muốn xóa bài viết này không ?
Bạn có chắc chắn muốn xóa bình luận này không ?
Java 9 try-with-resources Improvement
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
1. Java 7 try-with-resources
This is the way we use it from Java 7:
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) {
// ...
}
2. Java 9 try-with-resources improvement
Java 9 make things simple:
https://grokonez.com/java/java-9/java-9-try-resources-improvement
Java 9 try-with-resources Improvement





