2

在 Java 7 中,而不是

        try {
              fos = new FileOutputStream("movies.txt");
              dos = new DataOutputStream(fos);
              dos.writeUTF("Java 7 Block Buster");
        } catch (IOException e) {
              e.printStackTrace();
        } finally {

              try {
                    fos.close();
                    dos.close();

              } catch (IOException e) {
                    // log the exception
              }
        }

你可以这样做

        try (FileOutputStream fos = new FileOutputStream("movies.txt");
              DataOutputStream dos = new DataOutputStream(fos)) {
              dos.writeUTF("Java 7 Block Buster");
        } catch (IOException e) {
              // log the exception
        }

但我正在使用第 3 方 API,需要.close()调用此 API 来清理开放资源

try (org.pdfclown.files.File file = new org.pdfclown.files.File("movies.pdf")) {
         ...
}

Java 7 如何知道如何处理这样的第 3 方 API?它如何知道调用什么方法?

4

3 回答 3

10

Java 7 引入了“try-with-resources”。括号中的参数必须实现AutoCloseable定义close方法的接口。

我猜这个org.pdfclown.files.File类实现了AutoCloseable接口。

编辑

确实实现的Closeable接口在 Java 7org.pdfclown.files.File中扩展AutoCloseable。所以它应该在 Java 7 中工作,因为org.pdfclown.files.File确实实现AutoCloseable了,即使它间接地这样做。

于 2013-08-26T23:07:42.733 回答
6

如果您的 3rd 方类实现AutoClosable接口,它将运行良好

我已经在这里这里检查了pdfclown源代码,但它似乎没有实现AutoClosable

这是File.java源代码的重要部分:

public final class File
  implements Closeable

但是,正如其他答案和评论中提到的, Closable扩展了AutoClosable

于 2013-08-26T23:07:51.140 回答
3

在 java 7 中,编译器知道任何实现 AutoCloseable 并被声明为try-with-resources语句的一部分的类,以调用 close 方法作为 finally 块的一部分。

于 2013-08-26T23:07:35.247 回答