Check if file exists without creating it

When you instantiate a File, you’re not creating anything on disk but just building an object on which you can call some methods, like exists().

That’s fine and cheap, don’t try to avoid this instantiation.

The File instance has only two fields:

private String path;
private transient int prefixLength;

And here is the constructor :

public File(String pathname) {
    if (pathname == null) {
        throw new NullPointerException();
    }
    this.path = fs.normalize(pathname);
    this.prefixLength = fs.prefixLength(this.path);
}

As you can see, the File instance is just an encapsulation of the path. Creating it in order to call exists() is the correct way to proceed. Don’t try to optimize it away.

Leave a Comment