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发行说明。
The Path
class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path. Path
类包括各种方法,可用于获取有关路径的信息、访问路径元素、将路径转换为其他形式或提取路径的部分。There are also methods for matching the path string and methods for removing redundancies in a path. 还有用于匹配路径字符串的方法和用于删除路径中冗余的方法。This lesson addresses these 本课程介绍这些Path
methods, sometimes called syntactic operations, because they operate on the path itself and don't access the file system.Path
方法,有时称为语法操作,因为它们在路径本身上操作,不访问文件系统。
This section covers the following:本节包括以下内容:
A Path
instance contains the information used to specify the location of a file or directory. Path
实例包含用于指定文件或目录位置的信息。At the time it is defined, a 在定义Path
is provided with a series of one or more names. Path
时,会为它提供一系列一个或多个名称。A root element or a file name might be included, but neither are required. 可以包含根元素或文件名,但两者都不是必需的。A Path
might consist of just a single directory or file name.Path
可能只包含一个目录或文件名。
You can easily create a 您可以通过从Path
object by using one of the following get
methods from the Paths
(note the plural) helper class:Paths
(注意复数形式)助手类使用以下get
方法之一轻松创建Path
对象:
Path p1 = Paths.get("/tmp/foo"); Path p2 = Paths.get(args[0]); Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
The Paths.get
method is shorthand for the following code:Paths.get
方法是以下代码的简写:
Path p4 = FileSystems.getDefault().getPath("/users/sally");
The following example creates 下面的示例创建/u/joe/logs/foo.log
assuming your home directory is /u/joe
, or C:\joe\logs\foo.log
if you are on Windows./u/joe/logs/foo.log
,假设您的主目录是/u/joe
,如果您在Windows上,则创建C:\joe\logs\foo.log
。
Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log");
You can think of the 您可以将Path
as storing these name elements as a sequence. Path
视为将这些名称元素存储为序列。The highest element in the directory structure would be located at index 0. 目录结构中的最高元素将位于索引0处。The lowest element in the directory structure would be located at index 目录结构中最低的元素将位于索引[n-1]
, where n
is the number of name elements in the Path
. [n-1]
,其中n
是Path
中名称元素的数量。Methods are available for retrieving individual elements or a subsequence of the 方法可用于使用这些索引检索单个元素或Path
using these indexes.Path
的子序列。
The examples in this lesson use the following directory structure.本课程中的示例使用以下目录结构。
The following code snippet defines a 以下代码段定义了一个Path
instance and then invokes several methods to obtain information about the path:Path
实例,然后调用多个方法以获取有关该路径的信息:
// None of these methods requires that the file corresponding // to the Path exists. // Microsoft Windows syntax Path path = Paths.get("C:\\home\\joe\\foo"); // Solaris syntax Path path = Paths.get("/home/joe/foo"); System.out.format("toString: %s%n", path.toString()); System.out.format("getFileName: %s%n", path.getFileName()); System.out.format("getName(0): %s%n", path.getName(0)); System.out.format("getNameCount: %d%n", path.getNameCount()); System.out.format("subpath(0,2): %s%n", path.subpath(0,2)); System.out.format("getParent: %s%n", path.getParent()); System.out.format("getRoot: %s%n", path.getRoot());
Here is the output for both Windows and the Solaris OS:以下是Windows和Solaris操作系统的输出:
toString |
/home/joe/foo |
C:\home\joe\foo |
Path . Path 的字符串表示形式。Filesystems.getDefault().getPath(String) or Paths.get (the latter is a convenience method for getPath ), the method performs minor syntactic cleanup. Filesystems.getDefault().getPath(String) 或Paths.get (后者是getPath 的一个方便方法)创建的,则该方法将执行较小的语法清理。//home/joe/foo to /home/joe/foo .//home/joe/foo 更正为/home/joe/foo 。 |
getFileName |
foo |
foo |
|
getName(0) |
home |
home |
|
getNameCount |
3 |
3 |
|
subpath(0,2) |
home/joe |
home\joe |
Path (not including a root element) as specified by the beginning and ending indexes.Path 子序列(不包括根元素)。 |
getParent |
/home/joe |
\home\joe |
|
getRoot |
/ |
C:\ |
The previous example shows the output for an absolute path. 上一个示例显示了绝对路径的输出。In the following example, a relative path is specified:在以下示例中,指定了相对路径:
// Solaris syntax Path path = Paths.get("sally/bar"); or // Microsoft Windows syntax Path path = Paths.get("sally\\bar");
Here is the output for Windows and the Solaris OS:以下是Windows和Solaris操作系统的输出:
toString |
sally/bar |
sally\bar |
getFileName |
bar |
bar |
getName(0) |
sally |
sally |
getNameCount |
2 |
2 |
subpath(0,1) |
sally |
sally |
getParent |
sally |
sally |
getRoot |
null |
null |
Many file systems use "." notation to denote the current directory and ".." to denote the parent directory. 许多文件系统使用“.”表示当前目录,“..”表示父目录。You might have a situation where a 您可能会遇到Path
contains redundant directory information. Path
包含冗余目录信息的情况。Perhaps a server is configured to save its log files in the "可能服务器配置为将其日志文件保存在“/dir/logs/.
" directory, and you want to delete the trailing "/.
" notation from the path./dir/logs/.
”目录中,您希望从路径中删除尾随的“/.
”符号。
The following examples both include redundancies:以下示例均包括冗余:
/home/./joe/foo /home/sally/../joe/foo
The normalize
method removes any redundant elements, which includes any ".
" or "directory/..
" occurrences. normalize
方法删除任何冗余元素,其中包括任何出现的“.
”或“directory/..
”项。Both of the preceding examples normalize to 前面的两个示例都规范化为/home/joe/foo
./home/joe/foo
。
It is important to note that 需要注意的是,normalize
doesn't check at the file system when it cleans up a path. normalize
在清理路径时不会检查文件系统。It is a purely syntactic operation. 这是一个纯粹的语法操作。In the second example, if 在第二个示例中,如果sally
were a symbolic link, removing sally/..
might result in a Path
that no longer locates the intended file.sally
是符号链接,则删除sally/..
可能导致Path
不再定位所需文件。
To clean up a path while ensuring that the result locates the correct file, you can use the 要在确保结果找到正确文件的同时清理路径,可以使用toRealPath
method. toRealPath
方法。This method is described in the next section, Converting a Path.此方法将在下一节,转换路径中介绍。
You can use three methods to convert the 可以使用三种方法转换Path
. Path
。If you need to convert the path to a string that can be opened from a browser, you can use 如果需要将路径转换为可以从浏览器打开的字符串,可以使用toUri
. toUri
。For example:例如:
Path p1 = Paths.get("/home/logfile"); // Result is file:///home/logfile System.out.format("%s%n", p1.toUri());
The toAbsolutePath
method converts a path to an absolute path. toAbsolutePath
方法将路径转换为绝对路径。If the passed-in path is already absolute, it returns the same 如果传入的路径已经是绝对路径,则返回相同的Path
object. Path
对象。The toAbsolutePath
method can be very helpful when processing user-entered file names. toAbsolutePath
方法在处理用户输入的文件名时非常有用。For example:例如:
public class FileTest { public static void main(String[] args) { if (args.length < 1) { System.out.println("usage: FileTest file"); System.exit(-1); } // Converts the input string to a Path object. Path inputPath = Paths.get(args[0]); // Converts the input Path // to an absolute path. // Generally, this means prepending // the current working // directory. If this example // were called like this: // java FileTest foo // the getRoot and getParent methods // would return null // on the original "inputPath" // instance. Invoking getRoot and // getParent on the "fullPath" // instance returns expected values. Path fullPath = inputPath.toAbsolutePath(); } }
The toAbsolutePath
method converts the user input and returns a Path
that returns useful values when queried. toAbsolutePath
方法转换用户输入并返回一个路径,该路径在查询时返回有用的值。The file does not need to exist for this method to work.该文件不需要存在,此方法才能工作。
The toRealPath
method returns the real path of an existing file. toRealPath
方法返回现有文件的实际路径。This method performs several operations in one:此方法一次执行多个操作:
true
is passed to this method and the file system supports symbolic links, this method resolves any symbolic links in the path.true
传递给此方法,并且文件系统支持符号链接,则此方法解析路径中的任何符号链接。Path
is relative, it returns an absolute path.Path
是相对的,则返回绝对路径。Path
contains any redundant elements, it returns a path with those elements removed.Path
包含任何冗余元素,它将返回删除这些元素的路径。This method throws an exception if the file does not exist or cannot be accessed. 如果文件不存在或无法访问,此方法将引发异常。You can catch the exception when you want to handle any of these cases. 当您想要处理这些情况时,您可以捕获异常。For example:例如:
try { Path fp = path.toRealPath(); } catch (NoSuchFileException x) { System.err.format("%s: no such" + " file or directory%n", path); // Logic for case when file doesn't exist. } catch (IOException x) { System.err.format("%s%n", x); // Logic for other sort of file error. }
You can combine paths by using the 可以使用resolve
method. resolve
方法组合路径。You pass in a partial path , which is a path that does not include a root element, and that partial path is appended to the original path.传入部分路径,该路径不包含根元素,并且该部分路径将附加到原始路径。
For example, consider the following code snippet:例如,考虑下面的代码片段:
// Solaris Path p1 = Paths.get("/home/joe/foo"); // Result is /home/joe/foo/bar System.out.format("%s%n", p1.resolve("bar")); or // Microsoft Windows Path p1 = Paths.get("C:\\home\\joe\\foo"); // Result is C:\home\joe\foo\bar System.out.format("%s%n", p1.resolve("bar"));
Passing an absolute path to the 将绝对路径传递给resolve
method returns the passed-in path:resolve
方法将返回传入的路径:
// Result is /home/joe Paths.get("foo").resolve("/home/joe");
A common requirement when you are writing file I/O code is the capability to construct a path from one location in the file system to another location. 编写文件I/O代码时的一个常见要求是能够构造从文件系统中的一个位置到另一个位置的路径。You can meet this using the 您可以使用relativize
method. relativize
方法来实现这一点。This method constructs a path originating from the original path and ending at the location specified by the passed-in path. 此方法构造一条源于原始路径并在传入路径指定的位置结束的路径。The new path is relative to the original path.新路径相对于原始路径。
For example, consider two relative paths defined as 例如,考虑两个相对路径定义为joe
and sally
:joe
和sally
:
Path p1 = Paths.get("joe"); Path p2 = Paths.get("sally");
In the absence of any other information, it is assumed that 在没有任何其他信息的情况下,假设joe
and sally
are siblings, meaning nodes that reside at the same level in the tree structure. joe
和sally
是同辈,这意味着节点位于树结构中的同一级别。To navigate from 要从joe
to sally
, you would expect to first navigate one level up to the parent node and then down to sally
:joe
导航到sally
,您需要先向上导航一级到父节点,然后向下导航到sally
:
// Result is ../sally Path p1_to_p2 = p1.relativize(p2); // Result is ../joe Path p2_to_p1 = p2.relativize(p1);
Consider a slightly more complicated example:考虑一个稍微复杂的例子:
Path p1 = Paths.get("home"); Path p3 = Paths.get("home/sally/bar"); // Result is sally/bar Path p1_to_p3 = p1.relativize(p3); // Result is ../.. Path p3_to_p1 = p3.relativize(p1);
In this example, the two paths share the same node, 在本例中,两条路径共享同一个节点home
. home
。To navigate from 要从home
to bar
, you first navigate one level down to sally
and then one more level down to bar
. home
导航到bar
,首先要向下导航一层到sally
,然后再向下导航一层到bar
。Navigating from 从bar
to home
requires moving up two levels.bar
导航到home
需要向上移动两层。
A relative path cannot be constructed if only one of the paths includes a root element. 如果只有一个路径包含根元素,则无法构造相对路径。If both paths include a root element, the capability to construct a relative path is system dependent.如果两条路径都包含根元素,则构建相对路径的能力取决于系统。
The recursive 递归Copy
example uses the relativize
and resolve
methods.Copy
示例使用Relative
和resolve
方法。
The Path
class supports equals
, enabling you to test two paths for equality. Path
类支持equals
,使您能够测试两条路径是否相等。The startsWith
and endsWith
methods enable you to test whether a path begins or ends with a particular string. startsWith
和endsWith
方法使您能够测试路径是以特定字符串开始还是以特定字符串结束。These methods are easy to use. 这些方法很容易使用。For example:例如:
Path path = ...; Path otherPath = ...; Path beginning = Paths.get("/home"); Path ending = Paths.get("foo"); if (path.equals(otherPath)) { // equality logic here } else if (path.startsWith(beginning)) { // path begins with "/home" } else if (path.endsWith(ending)) { // path ends with "foo" }
The Path
class implements the Iterable
interface. Path
类实现Iterable
接口。The iterator
method returns an object that enables you to iterate over the name elements in the path. iterator
方法返回一个对象,该对象使您能够迭代路径中的name元素。The first element returned is that closest to the root in the directory tree. 返回的第一个元素是目录树中最接近根的元素。The following code snippet iterates over a path, printing each name element:以下代码段在路径上迭代,打印每个名称元素:
Path path = ...; for (Path name: path) { System.out.println(name); }
The Path
class also implements the Comparable
interface. Path
类还实现了Comparable
接口。You can compare 您可以使用Path
objects by using compareTo
which is useful for sorting.compareTo
来比较Path
对象,compareTo
对排序很有用。
You can also put 还可以将Path
objects into a Collection
. Path
对象放入Collection
中。See the Collections trail for more information about this powerful feature.有关此强大功能的更多信息,请参阅集合教程。
When you want to verify that two 如果要验证两个Path
objects locate the same file, you can use the isSameFile
method, as described in Checking Whether Two Paths Locate the Same File.Path
对象是否定位同一文件,可以使用isSameFile
方法,如检查两个路径是否定位同一文件中所述。