I am trying to find if given path is possible child of another path using java. Both path may not exist.
Say c:\\Program Files\\My Company\\test\\My App
Surprisingly there is no simple, yet functional solution.
The accepted answer does consider same directories as child, which is wrong.
Here is one using java.nio.file.Path API only:
static boolean isChildPath(Path parent, Path child){
Path pn = parent.normalize();
Path cn = child.normalize();
return cn.getNameCount() > pn.getNameCount() && cn.startsWith(pn);
}
Test cases:
@Test
public void testChildPath() {
assertThat(isChildPath(Paths.get("/FolderA/FolderB/F"), Paths.get("/FolderA/FolderB/F"))).isFalse();
assertThat(isChildPath(Paths.get("/FolderA/FolderB/F"), Paths.get("/FolderA/FolderB/F/A"))).isTrue();
assertThat(isChildPath(Paths.get("/FolderA/FolderB/F"), Paths.get("/FolderA/FolderB/F/A.txt"))).isTrue();
assertThat(isChildPath(Paths.get("/FolderA/FolderB/F"), Paths.get("/FolderA/FolderB/F/../A"))).isFalse();
assertThat(isChildPath(Paths.get("/FolderA/FolderB/F"), Paths.get("/FolderA/FolderB/FA"))).isFalse();
assertThat(isChildPath(Paths.get("FolderA"), Paths.get("FolderA"))).isFalse();
assertThat(isChildPath(Paths.get("FolderA"), Paths.get("FolderA/B"))).isTrue();
assertThat(isChildPath(Paths.get("FolderA"), Paths.get("FolderA/B"))).isTrue();
assertThat(isChildPath(Paths.get("FolderA"), Paths.get("FolderAB"))).isFalse();
assertThat(isChildPath(Paths.get("/FolderA/FolderB/F"), Paths.get("/FolderA/FolderB/F/Z/X/../A"))).isTrue();
}