Documentation

The Java™ Tutorials
Hide TOC
Path Operations路径操作
Trail: Essential Java Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)
Subsection: The Path Class

Path Operations路径操作

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:本节包括以下内容:

Creating a Path创建路径

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");

Retrieving Information about a Path检索有关路径的信息

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],其中nPath中名称元素的数量。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.本课程中的示例使用以下目录结构。

Sample directory structure

Sample 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操作系统的输出:

Method Invoked调用的方法 Returns in the Solaris OSSolaris操作系统中的返回 Returns in Microsoft Windows在Microsoft Windows中返回 Comment注释
toString /home/joe/foo C:\home\joe\foo Returns the string representation of the Path. 返回Path的字符串表示形式。If the path was created using 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的一个方便方法)创建的,则该方法将执行较小的语法清理。For example, in a UNIX operating system, it will correct the input string //home/joe/foo to /home/joe/foo.例如,在UNIX操作系统中,它会将输入字符串//home/joe/foo更正为/home/joe/foo
getFileName foo foo Returns the file name or the last element of the sequence of name elements.返回文件名或名称元素序列的最后一个元素。
getName(0) home home Returns the path element corresponding to the specified index. 返回与指定索引对应的路径元素。The 0th element is the path element closest to the root.第0个元素是距离根最近的路径元素。
getNameCount 3 3 Returns the number of elements in the path.返回路径中的元素数。
subpath(0,2) home/joe home\joe Returns the subsequence of the Path (not including a root element) as specified by the beginning and ending indexes.返回由起始索引和结束索引指定的Path子序列(不包括根元素)。
getParent /home/joe \home\joe Returns the path of the parent directory.返回父目录的路径。
getRoot / C:\ Returns the root of the path.返回路径的根。

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操作系统的输出:

Method Invoked调用的方法 Returns in the Solaris OSSolaris操作系统中的返回 Returns in Microsoft Windows在Microsoft Windows中返回
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

Removing Redundancies From a Path从路径中删除冗余

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.此方法将在下一节,转换路径中介绍。

Converting a Path转换路径

You can use three methods to convert the Path. 可以使用三种方法转换PathIf you need to convert the path to a string that can be opened from a browser, you can use toUri. 如果需要将路径转换为可以从浏览器打开的字符串,可以使用toUriFor 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:此方法一次执行多个操作:

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.
}

Joining Two Paths连接两条路径

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");

Creating a Path Between Two Paths在两条路径之间创建路径

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:例如,考虑两个相对路径定义为joesally

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. 在没有任何其他信息的情况下,假设joesally是同辈,这意味着节点位于树结构中的同一级别。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. 在本例中,两条路径共享同一个节点homeTo navigate from home to bar, you first navigate one level down to sally and then one more level down to bar. 要从home导航到bar,首先要向下导航一层到sally,然后再向下导航一层到barNavigating 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示例使用Relativeresolve方法。

Comparing Two Paths比较两条路径

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. startsWithendsWith方法使您能够测试路径是以特定字符串开始还是以特定字符串结束。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方法,如检查两个路径是否定位同一文件中所述。


Previous page: The Path Class
Next page: File Operations