Documentation

The Java™ Tutorials
Hide TOC
Checking a File or Directory检查文件或目录
Trail: Essential Java Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)

Checking a File or Directory检查文件或目录

You have a Path instance representing a file or directory, but does that file exist on the file system? 您有一个表示文件或目录的Path实例,但该文件是否存在于文件系统中?Is it readable? Writable? Executable?它可读吗?可写的?可执行文件?

Verifying the Existence of a File or Directory验证文件或目录是否存在

The methods in the Path class are syntactic, meaning that they operate on the Path instance. Path类中的方法是语法的,这意味着它们对Path实例进行操作。But eventually you must access the file system to verify that a particular Path exists, or does not exist. 但最终您必须访问文件系统以验证特定Path是否存在。You can do so with the exists(Path, LinkOption...) and the notExists(Path, LinkOption...) methods. 您可以使用exists(Path, LinkOption...)方法和notExists(Path, LinkOption...)方法来实现。Note that !Files.exists(path) is not equivalent to Files.notExists(path). 请注意!Files.exists(path)不等于Files.notExists(path)When you are testing a file's existence, three results are possible:测试文件是否存在时,可能会出现三种结果:

If both exists and notExists return false, the existence of the file cannot be verified.如果existsnotExists都返回false,则无法验证文件是否存在。

Checking File Accessibility检查文件可访问性

To verify that the program can access a file as needed, you can use the isReadable(Path), isWritable(Path), and isExecutable(Path) methods.要验证程序是否可以根据需要访问文件,可以使用isReadable(Path)isWritable(Path)isExecutable(Path)方法。

The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.下面的代码段验证特定文件是否存在,以及程序是否能够执行该文件。

Path file = ...;
boolean isRegularExecutableFile = Files.isRegularFile(file) &
         Files.isReadable(file) & Files.isExecutable(file);

Note: Once any of these methods completes, there is no guarantee that the file can be accessed. 一旦这些方法中的任何一个完成,就不能保证可以访问该文件。A common security flaw in many applications is to perform a check and then access the file. 许多应用程序中的一个常见安全缺陷是执行检查,然后访问文件。For more information, use your favorite search engine to look up TOCTTOU (pronounced TOCK-too). 有关更多信息,请使用您喜爱的搜索引擎查找TOCTTOU(发音TOCK-too)。

Checking Whether Two Paths Locate the Same File检查两个路径是否定位同一个文件

When you have a file system that uses symbolic links, it is possible to have two different paths that locate the same file. 如果文件系统使用符号链接,则可能有两个不同的路径来定位同一个文件。The isSameFile(Path, Path) method compares two paths to determine if they locate the same file on the file system. isSameFile(Path, Path)方法比较两个路径,以确定它们是否在文件系统上找到相同的文件。For example:例如:

Path p1 = ...;
Path p2 = ...;

if (Files.isSameFile(p1, p2)) {
    // Logic when the paths locate the same file
}

Previous page: File Operations
Next page: Deleting a File or Directory