Мы можем сгенерировать все подпути, начиная с самого длинного из возможных, и проверить, какие из них равны:
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