Home  >  Article  >  Java  >  How to declare multiple resources in try-with-resources statement in Java 9?

How to declare multiple resources in try-with-resources statement in Java 9?

王林
王林forward
2023-08-25 22:57:021276browse

在Java 9中如何在try-with-resources语句中声明多个资源?

In Java 9, the Try-with-resources statement has been improved. If we already have a resource that is final or equivalent to a final variable, then we can use that variable in the try-with-resources statement without declaring a new variable in the try-with-resources statement .

We can declare multiple resources in the try block. The try initialization block can have any number of resources, which can be null or non-null.

In the following example, we can declare multiple resources in the try-with-resources statement.

Example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

public class MultipleResourcesTest {
   public static void main(String args[]) throws IOException {
      System.out.println(readData("test"));
   }
   static String <strong>readData</strong>(String message) throws IOException {
      <strong>try</strong>(Reader inputString = new StringReader(message);
      BufferedReader br = new BufferedReader(inputString)) {
         return br.readLine();
      }
   }
}

Output

<strong>test</strong>

The above is the detailed content of How to declare multiple resources in try-with-resources statement 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