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

后端 未结 5 1557
忘了有多久
忘了有多久 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 13:03

    The resolve(Path) is a method for creating a new Path by joining an existing path to the current 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

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

    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
    

提交回复
热议问题