java isfile exists,Java File.exists()与File.isFile()

Java的File.exists()方法在处理特殊文件如命名管道、套接字或设备文件时显得尤为有用,因为它能检查这些非常规文件系统对象是否存在,而File.isFile()和File.isDirectory()则会返回false。例如,在Unix兼容系统中,/dev/null是一个设备文件。在处理大量文件时,exists()可能会影响性能,具体取决于文件系统、JVM实现和操作系统等因素。
摘要由CSDN通过智能技术生成

I'm unable to think of a realistic use case for the method java.io.File.exists() or its equivalent in Java 7 java.nio.file.Files.exists(Path). It seems that isFile() or isDirectory() would be preferable in all cases (or canRead(), canWrite(), etc.).

For example, in How do I check if a file exists in Java?, the accepted answer seems silly, as the second answer points out.

Can anyone give an example where it's useful to know that a thing exists, without knowing whether the thing is a file or directory?

EDIT: I understand what File.exists() does. My question is, when would that functionality ever help someone? I'm searching for an example like, "Use File.exists() when _ _ _ _ _ _, because neither File.isFile() nor File.isDirectory() add any value in that case."

In retrospect, I think my confusion here was regarding two seemingly contradictory statements in the JavaDoc of the File class. The first sentence defines the class as,

An abstract representation of file and directory pathnames.

That sounds like a clear dichotomy; but further in, the doc counters it with,

Instances of this class may or may not denote an actual file-system object such as a file or a directory.

I think an example of a third file-system object would have helped immensely in the documentation; but that category seems to lack even a name, resulting in the awkward phrasing of the JavaDoc for the Files class: a collection of static methods,

that operate on files, directories, or other types of files.

In the accepted answer, @koral refers to these other types as "special files". That seems apt to me. They are so special, I didn't know they existed.

解决方案

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().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值