Why Java io. File does not implement autoclosable?

See English answer > why Java io. File doesn’t have a close() method? 5

try (File file = new File(FILE_NAME)) {
        file.delete();          
    }

The error is:

There are no files listed in the autoclosable document in the Java document: http://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html

So what is the suggested alternative to adding catch blocks?

Solution

As Jeffrey said in his comments on this issue, you need to distinguish between file and InputStream, for example: FileInputStream

try (FileInputStream fs = new FileInputStream (new File(FILE_NAME))) {
    // do what you want with the stream
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>