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

后端 未结 5 1556
忘了有多久
忘了有多久 2021-02-07 12:12
Path p1 = Paths.get(\"/Users/jack/Documents/text1.txt\");
Path p2 = Paths.get(\"/Users/jack/text2.txt\");
Path result1 = p1.resolve(p2);
Path result2 = p1.relativize(p2)         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 12:53

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

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


    Path resolve(Path other)

    In the general use case of resolve(), you want to return a new Path object where you will join this Path object to the Path parameter that is a relative Path such as :

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

    Here result1 will be the path join of p1 and p2, that is : /Users/jack/text1.txt.

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

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

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

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

    Path relativize(Path other)

    The doc says more specifically :

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

    It means that the returned Path is the relative path of the Path parameter relatively to this Path.

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

    We will check that with your example :

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

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

    Paths.of("/Users/jack/Documents/text1.txt").resolve("../../text2.txt")
    
    returns -> /Users/jack/text2.txt
    

提交回复
热议问题