在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
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做
try (FileOutputStream fos = new FileOutputStream("movies.txt");
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeUTF("Java 7 Block Buster");
} catch (IOException e) {
// log the exception
}
Run Code Online (Sandbox Code Playgroud)
但我正在使用第三方API,此API需要.close()调用以清理开放资源
try (org.pdfclown.files.File file = new org.pdfclown.files.File("movies.pdf")) {
...
}
Run Code Online (Sandbox Code Playgroud)
Java 7如何知道如何处理这样的第三方API?它怎么知道叫什么方法?
rge*_*man 10
Java 7引入了"try-with-resources".括号中的参数必须实现AutoCloseable接口,该接口定义close方法.
我猜这个org.pdfclown.files.File类实现了AutoCloseable接口.
编辑
实现的Closeable接口在Java 7中org.pdfclown.files.File扩展AutoCloseable.因此它应该在Java 7中工作,因为org.pdfclown.files.File它实现了AutoCloseable,即使它间接地这样做.
如果您的第三方类实现AutoClosable接口,它将运行良好
我在这里和这里检查了pdfclown源代码,但似乎它没有实现AutoClosable
以下是来源的重要部分File.java:
public final class File
implements Closeable
Run Code Online (Sandbox Code Playgroud)
但是,正如其他答案和评论中所提到的, Closable扩展了AutoClosable!