The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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?它可读吗?可写的?可执行文件?
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.exists
和notExists
都返回false
,则无法验证文件是否存在。
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);
TOCTTOU
(pronounced TOCK-too). TOCTTOU
(发音TOCK-too)。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 }