Home  >  Article  >  Java  >  What are the improvements to try-with-resources in Java 9?

What are the improvements to try-with-resources in Java 9?

WBOY
WBOYforward
2023-09-10 12:45:031484browse

Java 9中的try-with-resources有哪些改进?

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.

Example

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();
      }
   }
}

Output

<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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete