我们可以从最长的可能开始生成所有子路径,并检查哪两个相等:
private Path commonPath(Path path0, Path path1) {
if (path0.equals(path1)) {
return path0;
}
path0 = path0.normalize();
path1 = path1.normalize();
int minCount = Math.min(path0.getNameCount(), path1.getNameCount());
for (int i = minCount; i > 0; i--) {
Path sp0 = path0.subpath(0, i);
if (sp0.equals(path1.subpath(0, i))) {
String root = Objects.toString(path0.getRoot(), "");
return Paths.get(root, sp0.toString());
}
}
return path0.getRoot();
}
及用法:
Map<String, String> paths = new LinkedHashMap<>();
paths.put("/a/b/c", "/a/b/d");
paths.put("/a/", "/a/b/d");
paths.put("/f/b/c", "/a/b/d");
paths.put("/a/b/c/d/e", "/a/b/f/../c/g");
paths.put("C:/Winnt/System32", "C:/Winnt/System64");
paths.forEach((k, v) ->
System.out.println(
k + " = " + v + " => " + commonPath(Paths.get(k), Paths.get(v))));
上面的代码打印:
/a/b/c = /a/b/d => /a/b
/a/ = /a/b/d => /a
/f/b/c = /a/b/d => /
/a/b/c/d/e = /a/b/f/../c/g => /a/b/c
C:/Winnt/System32 = C:/Winnt/System64 => C:/Winnt