How to check if a given path is possible child of another path?

后端 未结 9 1007
不思量自难忘°
不思量自难忘° 2020-12-09 01:53

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

9条回答
  •  孤城傲影
    2020-12-09 02:09

    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();
    }
    

提交回复
热议问题