Creating a path between two paths in Java using the Path class

后端 未结 4 1977
梦如初夏
梦如初夏 2020-12-11 15:05

What does exactly mean this sentence from this oracle java tutorial:

A relative path cannot be constructed if only one of the paths includes a root

4条回答
  •  情歌与酒
    2020-12-11 15:47

    As other answers already mentioned this is due to the different roots in the path.

    To work around that, you can use toAbsolutePath().

    For example:

    public class AnotherOnePathTheDust {
      public static void main (String []args)
      {
        Path p1 = Paths.get("home").toAbsolutePath();
        Path p3 = Paths.get("/home/sally/bar").toAbsolutePath();
    
        Path p1_to_p3 = p1.relativize(p3);
    
        Path p3_to_p1 = p3.relativize(p1);
        System.out.println(p3_to_p1);
      }
    }
    

提交回复
热议问题