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 :-)
The thing you need to consider is if File. Exists is expensive in terms of the overall operation you intend to do, and whether or not you actually have any alternatives.
The exists() function is a part of the File class in Java. This function determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false.
To test to see if a file or directory exists, use the exists method of the Java File class, as shown in this example: File tmpDir = new File("/var/tmp"); boolean exists = tmpDir. exists(); The existing method of the Java File class returns true if the file or directory exists, and false otherwise.
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.
How this operation if performed the first time is entirely dependant on the filesystem. This is done by the OS and Java doesn't play any part.
In terms of performance, a read to a disk is required in all cases. This typically takes 8-12 ms. @Sven points out some storage could slower, but this relatively rare in cases where performance is important. You may have an additional delay if this is a network file system (usually relatively small but it depends on your network latency).
Everything else the OS and Java does is very short by comparison.
However, if you check the file exists repeatedly, a Disk access may not be required as the information can cached, in this case the time the OS takes and resources. One of the largest of these the objects File.exists() creates (you wouldn't think it would) however it encodes the file's name on every call creating a lot of objects. If you put File.exists() in a tight loop it can create 400MB of garbage per second. :(
Journaling filesystems work differently by keeping track of all the changes you make to a file system, however they don't change how you read the filesystem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With