Java 9 对 try-with-resources 做了哪些改进?\

javaobject oriented programmingprogramming更新于 2025/7/14 23:40:17

Try-with-Resources 是在 Java 7 中引入的,使用的目的是  在使用后自动关闭资源。限制是需要在 try 之前或 try 语句中声明资源,否则会抛出编译错误。

Java 9 对 try-with-resources 进行了改进,不再需要在 try 语句中声明对象。

在下面的例子中,我们实现了 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);
      try(breader) {
         while((line = breader.readLine()) != null) {
            System.out.println(line);
         }
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

输出

tutorialspoint

相关文章


有用资源