English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
try-with-resources is a feature in the JDK 7 introduces a new exception handling mechanism that can easily close resources in the try-catch block uses resources. The so-called resource refers to an object that must be closed after the program is completed. try-with-The resources statement ensures that each resource is closed at the end of the statement. All objects that implement the java.lang.AutoCloseable interface (including all objects that implement java.io.Closeable) can be used as resources.
try-with-The resources declaration is in the JDK 9 If you already have a resource that is final or equivalent to a final variable, you can use it in the try-with-use the variable in the resources statement without having to declare it in the try-with-declare a new variable in the resources statement.
import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData("test")); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (BufferedReader br1 = br) { return br1.readLine(); } } }
The output result is:
test
In the above example, we need to declare the resource br in the try statement block1then you can use it.
in Java 9 in this case, we do not need to declare the resource br1 you can use it and get the same result.
import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class Tester { public static void main(String[] args) throws IOException { System.out.println(readData("test")); } static String readData(String message) throws IOException { Reader inputString = new StringReader(message); BufferedReader br = new BufferedReader(inputString); try (br) { return br.readLine(); } } }
The execution output result is:
test
When dealing with resources that must be closed, use try-with-resources statement instead of try-finally statement. The generated code is more concise, clearer, and the generated exceptions are more useful. try-with-The resources statement makes it easier to write code that must close resources, and it will not fail, while using try-The finally statement is actually impossible.