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

标签 java nio2

关于您可以阅读的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

只要我理解整个想法就像问“我目前位于路径p1给出的位置,我如何到达路径p2 > 从这里?”.

但对我来说,鉴于 /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).

关于java - 包含 "dot directory"时的 Path.relativize 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34271760/

相关文章:

java - 当对象初始化时调用方法

java - 为什么仪表室测试出现错误 FOREIGN KEY 约束失败

java - undertow 网络服务器未绑定(bind)到远程地址

Java nio2 : map Path objects between filesystems without relying on toString

Java NIO2 并发完成处理程序

java - Spring Boot 2 权限提取器

java - 开发本地时 GAE Blob 消失

Java从int中获取数字,就像字符串的子串一样?

java - 在 Java 中列出文件的最快方法