在哪里使用 java.nio.file.Path 类的 resolve() 和 relativize() 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50551920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:40:56  来源:igfitidea点击:

Where to use resolve() and relativize() method of java.nio.file.Path class?

javapathresolve

提问by sagar varsani

Path p1 = Paths.get("/Users/Hyman/Documents/text1.txt");
Path p2 = Paths.get("/Users/Hyman/text2.txt");
Path result1 = p1.resolve(p2);
Path result2 = p1.relativize(p2);

System.out.println("result1: "+result1);
System.out.println("result2: "+result2);

OUTPUT

输出

result1: /Users/Hyman/text2.txt
result2: ../../text2.txt

I cannot understand how resolve()and relativize()works?

我不知道如何resolve()relativize()作品?

What is the actual use of result1and result2?

result1和的实际用途是result2什么?

采纳答案by Akshay Pethani

These are the code snippets from my code base that help you to understand the use of the resolve() method

这些是我的代码库中的代码片段,可帮助您了解 resolve() 方法的使用

private File initUsersText() throws Exception
{
    Path dir = testdir.getPath().toRealPath();
    FS.ensureDirExists(dir.toFile());
    File users = dir.resolve("users.txt").toFile();

    writeUser( users );
    return users;
}


private File initUsersText() throws Exception
{
    Path dir = testdir.getPath().toRealPath();
    FS.ensureDirExists(dir.toFile());
    File users = dir.resolve("users.txt").toFile();

    writeUser( users );
    return users;
}

And these are the examples of the use of relativize()

这些是使用 relativize() 的例子

public ScopePath pathToClassName(Path file) {
    if (!isValidClass(file))
        return null;

    Path relativePath = root.relativize(root.resolve(file));
    String withoutExtension = removeExtension(relativePath.toString());
    return new ScopePath(withoutExtension.replace(File.separator, "."));
}


private String getRelativePath(Path p) {
    String relativePath = packageDir.relativize(p)
            .toString();

    if (File.separator.equals("\")) {
        relativePath = relativePath.replace("\", "/");
    }

    return relativePath;
}

回答by QuakeCore

resolve(): Joins two paths.

resolve(): 连接两条路径。

relativize (): construct a path from one location in the file system to another location.

relativize (): 构造从文件系统中的一个位置到另一个位置的路径。

Output explanation:

输出说明:

result1: /Users/Hyman/text2.txt: because you passed in an absolute path, resolve()returns the passed in the path as is if it is an absolute path.

result1: /Users/Hyman/text2.txt: 因为你传入了一个绝对路径,所以resolve()返回传入的路径,就好像它是一个绝对路径一样。

result2: ../../text2.txt: to get to /Users/Hyman/text2.txtfrom /Users/Hyman/Documents/text1.txt"you need to to go two levels up, and then just select `text2.txt file.

result2: ../../text2.txt/Users/Hyman/text2.txt要从/Users/Hyman/Documents/text1.txt"你需要向上两级,然后选择`text2.txt文件。

回答by davidxxx

I cannot understand how resolve() and relativize() method works?

我无法理解 resolve() 和 relativize() 方法是如何工作的?

Path resolve(Path)resolves the given path against thispath.
Path relativize(Path)constructs a relative path of the given path against thispath .
These are reverse operations.

Path resolve(Path)根据路径解析给定this路径。
Path relativize(Path)根据 path 构造给定路径的相对this路径。
这些是反向操作。



Path resolve(Path other)

路径解析(路径其他)

In the general use case of resolve(), you want to return a new Pathobject where you will join this Pathobject to the Pathparameter that is a relative Pathsuch as :

在 的一般用例中resolve(),您希望返回一个新Path对象,您将在该Path对象中将此对象连接到作为Path相对的参数,Path例如:

Path p1 = Paths.get("/Users/Hyman");
Path p2 = Paths.get("text1.txt");
Path result1 = p1.resolve(p2);

Here result1will be the path join of p1and p2, that is : /Users/Hyman/text1.txt.

这里result1将是p1and的路径连接p2,即 : /Users/Hyman/text1.txt

In your example the parameter passed to the method is not a relative Pathbut an absolute :

在您的示例中,传递给该方法的参数不是相对的Path而是绝对的:

Path p1 = Paths.get("/Users/Hyman/Documents/text1.txt");
Path p2 = Paths.get("/Users/Hyman/text2.txt");
Path result1 = p1.resolve(p2); 

It makes no sense to "append" a Pathto another if the second is an absolute Path.
So the javadoc considers that in this case the parameter is returned as result of resolve():

Path如果第二个是绝对的,则将一个“附加”到另一个是没有意义的Path
因此,javadoc 认为在这种情况下,参数作为以下结果返回resolve()

If the other parameter is an absolute path then this method trivially returns other.

如果另一个参数是绝对路径,则此方法简单地返回 other。

Path relativize(Path other)

路径相对化(路径其他)

The doc says more specifically :

该文档更具体地说:

This method attempts to construct a relative path that when resolved against thispath, yields a path that locates the same file as the given path.

此方法尝试构造一个相对路径,当针对this路径解析时,该路径会生成一个与给定路径定位相同文件的路径。

It means that the returned Pathis the relative path of the Pathparameter relatively to thisPath.

表示返回的PathPath参数相对于 的相对路径thisPath

For example, if thispath is "/a/b"and the given path is "/a/b/c/d"then the resulting relative path would be "c/d".

例如,如果thispath is"/a/b"并且给定的 path is"/a/b/c/d"那么结果相对路径将是"c/d"

We will check that with your example :

我们将使用您的示例进行检查:

Path p1 = Paths.get("/Users/Hyman/Documents/text1.txt");
Path p2 = Paths.get("/Users/Hyman/text2.txt");
Path result2 = p1.relativize(p2);   
// result2= ../../text2.txt

The ../../text2.txtPath is expected as result as the relative path produced ( ../../text2.txt) resolved against thispath (/Users/Hyman/Documents/text1.txt) yields a path that locates the same file as the given path (/Users/Hyman/text2.txt) :

../../text2.txt路径被期待作为结果作为相对路径产生(../../text2.txt)解决了对this路径(/Users/Hyman/Documents/text1.txt)产生用于定位相同的文件中给定的路径(路径/Users/Hyman/text2.txt):

Paths.of("/Users/Hyman/Documents/text1.txt").resolve("../../text2.txt")

returns -> /Users/Hyman/text2.txt

回答by Imar

The resolve(Path)is a method for creating a new Path by joining an existing path to the current path.

resolve(Path)是一种通过将现有路径连接到当前路径来创建新路径的方法。

Path path1 = Paths.get("/test1/../test2");
Path path2 = Paths.get("test3");
System.out.println(path1.resolve(path2));

The result will be: /test1/../test2/test3

结果将是: /test1/../test2/test3

In fact, the method relativize(Path) is used for constructing the relative path from one Path object to another:

实际上,relativize(Path) 方法用于构造从一个 Path 对象到另一个的相对路径:

Path path1= Paths.get("E:\test1");
Path path2= Paths.get("E:\test2\test3");
System.out.println(path1.relativize(path2));
System.out.println(path2.relativize(path1));

The result will be:

结果将是:

..\test2\test3  relative path from path1 to path2
..\..\test1     relative path from path2 to path1