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

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-09-10 12:45:03
forward
1695 people have browsed it

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

Output

<strong>tutorialspoint</strong>
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template