在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
}
但我正在使用第三方API,此API要求调用.close()
来清理开放资源
try (org.pdfclown.files.File file = new org.pdfclown.files.File("movies.pdf")) {
...
}
Java 7如何知道如何处理这样的第三方API?它将如何知道要调用哪种方法?
答案 0 :(得分:10)
Java 7引入了"try-with-resources"。括号中的参数必须实现AutoCloseable
接口,该接口定义close
方法。
我猜测org.pdfclown.files.File
类实现了AutoCloseable
接口。
修改强>
Closeable
确实实现的org.pdfclown.files.File
接口在Java 7中扩展AutoCloseable
。所以它应该在Java 7中工作,因为org.pdfclown.files.File
确实实现了AutoCloseable
即使它间接地这样做了。
答案 1 :(得分:6)
如果您的第三方类实现了AutoClosable接口
,它将会运行良好我已查看pdfclown
来源here和here,但似乎没有实施AutoClosable
以下是File.java
来源的重要部分:
public final class File
implements Closeable
但,如其他答案和评论中所述,Closable延伸AutoClosable!
答案 2 :(得分:3)
在java 7中,编译器知道任何实现AutoCloseable的类并且被声明为try-with-resources语句的一部分,以调用close方法作为finally块的一部分。