Alex Rivera | Logout

How expensive is File.exists in Java

Asked 2011-06-12T09:20:01.777
34

I am wondering how File.exists() works. I'm not very aware of how filesystems work, so I should maybe start reading there first.

But for a quick pre information:

Is a call to File.exists() a single action for the filesystem, if that path and filename are registered in some journal? Or does the OS get the content of the directory and then scan through it for matches?

I presume this will be filesystem dependent, but maybe all filesystems use the quick approach?

I'm not talking about network and tape systems. Lets keep it to ntfs, extX, zfs, jfs :-)

Edit
Report

1 Answer

16

Measure the necessary time and see yourself. As you say it is absolutely file system dependent.

        long t1 = System.currentTimeMillis();
        ...Your File.exists call
        long t2 = System.currentTimeMillis();
        System.out.println("time: " + (t2 - t1) + " ms");

You will see that it will always give you different results, since it depends also on the way your OS caches data, on its load etc.

answered 2011-06-12T09:35:09.317

Your Answer