转载 

Java 9 Try-With-Resources 增强

分类:java    374人阅读    IT小君  2023-04-09 19:59

在 Java 7 和 8 中,我们可以使用 try-with-resource 块来声明可关闭的资源。任何实现的对象都java.lang.AutoCloseable可以在 try-with-resource 块中使用。以下是执行此操作的 Java 7/8 语法:

 try(InputStream stream1 = new InputStream(....);
     InputStream stream2 = new InputStream(....)){
    ....
 }

当上述块终止时,无论是正常终止还是由于异常终止,close()每个流对象的方法将按照它们声明的顺序自动调用。

 

Java 9 在使用 try-with-resource 块时提供了额外的灵活性,现在我们不再有在 try 括号内声明每个可关闭对象的限制,我们只需要使用它们的引用:

 InputStream stream1 = new InputStream(....);
 InputStream stream2 = new InputStream(....);
    ....
 try(stream1;stream2){
    ....
 }

例子

 

为简单起见,我们将使用 String 对象作为 InputStream 源。我们还将覆盖 close() 方法以了解它何时被调用。

public class TryWithResourceExample {
  public static void main(String[] args) throws IOException {
      InputStream inputStream = getInputStream();

      try (inputStream) {
          String s = new String(inputStream.readAllBytes());
          System.out.println(s);
      }

      System.out.println("after try-with-resource block");
  }

  public static InputStream getInputStream() {
      return new ByteArrayInputStream("test string".getBytes()) {
          @Override
          public void close() throws IOException {
              System.out.println("closing");
              super.close();
          }
      };
  }
}

 

输出

 

test string
closing
after try-with-resource block
支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»