为什么 java.io.File 没有实现 Autocloseable?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28529521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does java.io.File not implement Autocloseable?
提问by Salvador Valencia
After upgrading to Java 7 I get the following code flagged by Eclipse:
升级到 Java 7 后,我得到了 Eclipse 标记的以下代码:
try (File file = new File(FILE_NAME)) {
file.delete();
}
Error is:
错误是:
The resource type File does not implement java.lang.AutoCloseable
资源类型 File 没有实现 java.lang.AutoCloseable
And Java's documentation doesn't have File listed in the AutoCloseable docs: http://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
并且 Java 的文档没有在 AutoCloseable 文档中列出文件:http: //docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
So besides adding the catch block, what is the suggested alternative?
那么除了添加 catch 块之外,建议的替代方法是什么?
回答by Yoni
As Jeffrey said in the comment to the question, you need to differentiate between a File and an InputStream, e.g. FileInputStream. There is nothing to close in a File, but there is something to close in a stream or a reader.
正如杰弗里在对该问题的评论中所说,您需要区分 File 和 InputStream,例如 FileInputStream。在文件中没有什么要关闭的,但是在流或读取器中有要关闭的东西。
try (FileInputStream fs = new FileInputStream (new File(FILE_NAME))) {
// do what you want with the stream
}