当只有一个 Path 包含根元素时,为什么 Java 7 的新 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
非绝对路径是相对于某些未指定基本目录的。如果您有两个这样的路径,那么想象它们相对于相同(但仍未指定)基本目录是有意义的,然后询问其中一个相对于另一个的位置就有意义了。
另一方面,如果您有两个路径,其中只有一个是绝对路径,例如
/home/test
和home
,则不知道它们之间的关系是什么。例如,如果基本目录恰好是/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
andhome
there is no knowing what there relation is. For example if the base directory happens to be/home/test/blah
, thenhome
means/home/test/blah/home
and it should therefore relativize toblah/home
. But how would the method know how to inventblah
(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.