This question already has answers here:
Why java.io.File doesn't have a close() method?

(5个答案)


5年前关闭。




升级到Java 7之后,我得到了Eclipse标记的以下代码:
    try (File file = new File(FILE_NAME)) {
        file.delete();
    }

错误是:

资源类型文件未实现java.lang.AutoCloseable

而且Java的文档没有在AutoCloseable文档中列出File:
http://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html

因此,除了添加catch块之外,建议的替代方法是什么?

最佳答案

正如Jeffrey在对问题的评论中所说的那样,您需要区分File和InputStream,例如FileInputStream。
文件中没有要关闭的内容,但流或阅读器中有要关闭的内容。

try (FileInputStream fs = new FileInputStream (new File(FILE_NAME))) {
    // do what you want with the stream
}

10-04 21:38
查看更多