Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java.io.File not implement Autocloseable? [duplicate]

Tags:

java

After upgrading to Java 7 I get the following code flagged by Eclipse:

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

Error is:

The resource type File does not implement 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

So besides adding the catch block, what is the suggested alternative?

like image 206
Salvador Valencia Avatar asked Feb 15 '15 18:02

Salvador Valencia


1 Answers

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.

try (FileInputStream fs = new FileInputStream (new File(FILE_NAME))) {
    // do what you want with the stream
}
like image 67
Yoni Avatar answered Sep 28 '22 03:09

Yoni