Rol*_*all 13 java path relative-path
这个 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); }
}
Run Code Online (Sandbox Code Playgroud)
我通过使用"/ home/sally/bar"而不是"home/sally/bar"(没有root)获得的例外是这样的:
java.lang.IllegalArgumentException: 'other' is different type of Path
Run Code Online (Sandbox Code Playgroud)
为什么不起作用?他们所说的与系统的冲突是什么?
因为p1和p3根有不同.
如果你使用"/ home/sally/bar"代替"home/sally/bar" p3,那么p3.getRoot()将返回/但是p1.getRoot()为null.
在您阅读以下代码后,您就会知道为什么会遇到此异常(来自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");
Run Code Online (Sandbox Code Playgroud)
这里的系统依赖是指我假设的特定操作系统实现。因此,Linux 处理此问题的方式与 Windows 等不同。如果没有根路径(即以 / 开头的路径),则假定两个路径是同级路径,位于同一级别(即在 /home/sally 中)。因此,当您尝试相对化时,如果它们不在同一级别上,则无法保证非根路径存储在何处,如果您考虑一下,这是有道理的。这有帮助吗?