Path.relativize 包含 "dot directory" 时的行为

Path.relativize behaviour when "dot directory" is included

关于Path.relativize方法你可以阅读

[...] This method attempts to construct a relative path that when resolved against this path, yields a path that locates the same file as the given path. For example, on UNIX, if this path is "/a/b" and the given path is "/a/b/c/d" then the resulting relative path would be "c/d". [...]

所以这个

Path p1 = Paths.get("/a/b");
Path p2 = Paths.get("/a/b/c/d");
System.out.println(p1.relativize(p2));

输出

c\d

只要我理解整个思路就像在问"I'm currently in the location given by path p1, how do I get to path p2 from here?".

但对我来说,鉴于 /a/b/a/b/. 代表相同的位置,我希望上述问题的答案是相同的,而

Path p1 = Paths.get("/a/b/.");
Path p2 = Paths.get("/a/b/c/d");
System.out.println(p1.relativize(p2));

打印

..\c\d

相反。在这种情况下,如果我在 p1 给出的位置,应用 ..\c\d 我不会到达 p2 而是 \a\c\d,所以...有些不一致或我的比喻是错误的。那么,你能帮我理解我的比喻哪里错了以及为什么错了吗?

出于 p1 的目的,路径段 . 被认为只是另一个名称,而不是 当前目录 的特例。

如果你想让它表示当前目录,normalize路径。

The precise definition of this method is implementation dependent but in general it derives from this path, a path that does not contain redundant name elements. In many file systems, the "." and ".." are special names used to indicate the current directory and parent directory. In such file systems all occurrences of "." are considered redundant. If a ".." is preceded by a non-".." name then both names are considered redundant (the process to identify such names is repeated until it is no longer applicable).