为什么 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:45:13  来源:igfitidea点击:

Why does java.io.File not implement Autocloseable?

java

提问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/Au​​toCloseable.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
}