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

后端 未结 5 1571
忘了有多久
忘了有多久 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:37

    Path::resolve - Resolve the given path against this path.

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

    Path p1 = Paths.get("/usr");
    Path p2 = Paths.get("/etc");
    Path p3 = p1.resolve(p2); // returns /etc
    

    If other is an empty path then this method trivially returns this path.

    Path p1 = Paths.get("/usr");
    Path p2 = Paths.get("");
    Path p3 = p1.resolve(p2); // returns /usr
    

    Otherwise this method considers this path to be a directory and resolves the given path against this path.

    Path p1 = Paths.get("/usr");
    Path p2 = Paths.get("local");
    Path p3 = p1.resolve(p2); // returns /usr/local
    

    Path::relativize - Constructs a relative path between this path and a given path.

    Path p1 = Paths.get("/usr");
    Path p2 = Paths.get("/usr/local");
    Path p3 = p1.relativize(p2); // returns local
    

    This also means that

    Path p1 = Paths.get("/usr");
    Path p2 = Paths.get("/usr/../usr/local");
    Path p3 = p1.relativize(p2); // returns local
    

    But if the two paths are equal returns an empty path

    Path p1 = Paths.get("/usr");
    Path p2 = Paths.get("/usr/../usr");
    Path p3 = p1.relativize(p2); // returns empty path
    

提交回复
热议问题