Java File.exists() versus File.isFile()

社会主义新天地 提交于 2019-11-29 11:21:05

Answering to the last question of @jaco0646:

Use File.exists() when dealing with special files like named pipes, sockets or device files.

Those are not regular files nor directories nor symlinks so both File.isFile() and File.isDirectory() will return false while File.exists() will return true. For example /dev/null (on Unix compatible OSes) is a device file.

Theoretically there may be performance differences visible when processing large amounts of files. This depends also on filesystem, JVM implementation details, OS etc.

Eg. on Android File.exists() is implemented using access() system call while File.isFile()/File.isDirectory() use stat(). In this case processing stat() output requires more logic in userspace than access().

The only use case I can think of would be one for lock files, or something similar. A time where whether the file is a regular file or a directory is immaterial and the mere existence of something with that name is good enough to trigger program behavior.

Possibly also checking whether a cache exists. The cache could be implemented by different providers, some of which use a directory structure and some of which use a zip file (I'm making this up as I go, by the way -- I'm not saying this is a good idea).

Well it's a convenience to be able to set LinkOptions in the parameters. The actual API for this call is

static java.nio.file.Files.exists(Path path, LinkOption... options)

You might not want to follow symbolic links in the file path you specified. In this case, call Files.exists(path) - with link option NOFOLLOW_LINKS, and you're set.

It's also nice to have static methods when you don't really want to create more objects (like transient File objects) in your space than you need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!