使用Path类在Java中的两个路径之间创建路径

这个 oracle java教程中的这个句子究竟是什么意思:

如果只有一个路径包含根元素,则不能构造相对路径。 如果两个路径都包含根元素,则构造相对路径的能力取决于系统。

对于“系统依赖”,它们仅表示如果一个元素包含一个根,它只能在已编写的平台特定语法中工作吗? 我想这是他们唯一的意思。 还有其他方法可以阅读吗?

例如 :

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

我通过使用“/ home / sally / bar”而不是“home / sally / bar”(没有root)获得的例外是这样的:

  java.lang.IllegalArgumentException: 'other' is different type of Path 

为什么不起作用? 他们的意思是与系统的冲突是什么?

因为p1p3有不同的根。

如果对p3使用“/ home / sally / bar”而不是“home / sally / bar”,则p3.getRoot()将返回/p1.getRoot()为null。

在您阅读以下代码后,您将知道为什么会遇到此exception(来自http://cr.openjdk.java.net/~alanb/6863864/webrev.00/src/windows/classes/sun/nio/fs/ WindowsPath.java-.html Line374-375):

 // can only relativize paths of the same type if (this.type != other.type) throw new IllegalArgumentException("'other' is different type of Path"); 

这里依赖的系统是指我假设的特定OS实现。 因此Linux将以不同于Windows的方式处理这种情况,等等。如果没有根路径(即以/开头的路径),则假定两个路径都是兄弟姐妹,坐在同一级别(即/ home / sally)。 因此,当您尝试进行相对化时,如果它们不在同一级别,则无法保证存储非根路径的位置,这在您考虑它时是有意义的。 这有帮助吗?

我对你的例子进行了一些测试。 实际上你提到的例外只有当其中一条路径包含root而另一条路径不包含时(就像句子所说的那样),例如:

  • /家庭/萨利/条

如果两个路径都包含根,则可以正常工作 “依赖于系统”在Windows上可能就是这种情况:

  • C:\家
  • d:\家\莎莉\酒吧

以上给出以下例外:

 java.lang.IllegalArgumentException: 'other' has different root 

在Unix上,你永远不会遇到类似这样的东西(两个包含root的路径的例外 – 绝对路径)

正如其他已经提到的答案,这是由于路径的根源不同。

要解决此问题,您可以使用toAbsolutePath()

例如:

 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); } }