当只有一个 Path 包含根元素时,为什么 Java 7 的新 Path 对象不能相对化?

发布于 2024-12-01 23:35:47 字数 764 浏览 1 评论 0原文

根据 java.nio.file.Path

如果只有一个路径具有根组件,则无法构造相对路径。

为什么会这样呢?为什么不可能像这样相对化:

Path path1 = Paths.get("/home/test");
Path path2 = Paths.get("home");

// throws an IllegalArgumentException
Path path3 = path1.relativize(path2);

我曾想象 path3 会产生相对路径 ../。如果没有定义根元素,为什么 Path 返回一个表明两个目录位于文件系统中同一级别的结果是有效的,然而,当只有一个路径定义根元素时(如如上所示),无法确定相对路径?

IE

Path path1 = Paths.get("home/test");
Path path2 = Paths.get("user");

// results in ../../user
Path path3 = path1.relativize(path2);

As per java.nio.file.Path:

A relative path cannot be constructed if only one of the paths have a root component.

Why is this so? Why is it not possible to relativize like so:

Path path1 = Paths.get("/home/test");
Path path2 = Paths.get("home");

// throws an IllegalArgumentException
Path path3 = path1.relativize(path2);

I had imagined that path3 would result in the relative path ../. Why is it valid for Path to return a result that suggests that two directories sit at the same level within the file system if no root elements are defined, yet, when only one path defines a root element (as shown above), no relative path can be determined?

i.e.

Path path1 = Paths.get("home/test");
Path path2 = Paths.get("user");

// results in ../../user
Path path3 = path1.relativize(path2);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想你的星星会说话 2024-12-08 23:35:47

非绝对路径是相对于某些未指定基本目录的。如果您有两个这样的路径,那么想象它们相对于相同(但仍未指定)基本目录是有意义的,然后询问其中一个相对于另一个的位置就有意义了。

另一方面,如果您有两个路径,其中只有一个是绝对路径,例如 /home/testhome ,则不知道它们之间的关系是什么。例如,如果基本目录恰好是 /home/test/blah,则 home 表示 /home/test/blah/home 并且它因此应该相对于blah/home。但是该方法如何知道如何发明blah(或完全发明其他东西)?

使用相对路径的全部意义在于,我还没有告诉您该路径名的基本目录是什么。期望运行时库猜测我们明确没有告诉它的基本路径将完全违背该语义。

A non-absolute path is relative to some unspecified base directory. If you have two such paths, it will make some sense to imagine they are relative to the same (but still unspecified) base directory, and then it makes meaning to ask where one is with respect to the other.

On the other hand, if you have two paths of which only one is absolute, such as /home/test and home there is no knowing what there relation is. For example if the base directory happens to be /home/test/blah, then home means /home/test/blah/home and it should therefore relativize to blah/home. But how would the method know how to invent blah (or to invent something else entirely)?

The whole point of using a relative path is to say, I'm not telling you yet what the base directory for this pathname is going to be. Expecting the runtime library to guess the base path that we're explicitly not telling it would be completely counter to that semantics.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文