Home >Java >javaTutorial >What are the improvements to try-with-resources in Java 9?
Try-with-Resources Introduced in Java 7. The purpose of using it is to automatically close the resource after use. The limitation is that the resource needs to be declared before try or inside the try statement, otherwise a compilation error will be thrown.
Java 9 has improved try-with-resources, no longer need to declare the object inside the try statement.
In the following example, we implement the concept of try-with-resources.
import java.io.*; public class TryWithResourceTest { public static void main(String[] args) throws FileNotFoundException { String line; Reader reader = new StringReader("tutorialspoint"); BufferedReader breader = new BufferedReader(reader); <strong>try(breader)</strong> { while((line = breader.readLine()) != null) { System.out.println(line); } } catch(IOException ioe) { ioe.printStackTrace(); } } }
<strong>tutorialspoint</strong>
The above is the detailed content of What are the improvements to try-with-resources in Java 9?. For more information, please follow other related articles on the PHP Chinese website!