Path.relativize behaviour when “dot directory” is included

白昼怎懂夜的黑 提交于 2019-12-10 23:07:38

问题


About Path.relativize method you can read

[...] 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". [...]

So this

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

outputs

c\d

As long as I understand the whole idea is like asking "I'm currently in the location given by path p1, how do I get to path p2 from here?".

But to me, given that /a/b and /a/b/. represent the same location, I'd expect the answer to the above question to be the same, while

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

prints

..\c\d

instead. In this case, if I'm in the location given by p1, applying ..\c\d I won't get to p2 but to \a\c\d, so... Either there's some inconsistency or my metaphore is wrong. So, could you help me to understand where and why is my metaphore wrong?


回答1:


The path segment ., for the purposes of p1, is considered just another name, not a special case for the current directory.

If you want it to mean the current directory, normalize the path.

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).



来源:https://stackoverflow.com/questions/34271760/path-relativize-behaviour-when-dot-directory-is-included

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!