Java:检查路径是否是文件的父级

时间:2015-02-24 14:16:10

标签: java path filepath

我似乎无法找到解决方案。

我有两条路,比如:

D:/Views/me/a.b AND D:/Views/me/a

D:/Views/me/a.b AND D:/Views/me/a.b/x/y

我必须确保,一个文件/目录不是另一个的子文件。 我试过了Contains,但在这种情况下它对我不起作用?

4 个答案:

答案 0 :(得分:4)

我认为java.nio.file中的PathPaths在这里很有用(如果你至少有Java 7)。

public static void main(String[] args) {
    Path p1 = Paths.get("D:/Views/me/a.b");
    Path p2 = Paths.get("D:/Views/me/a");
    System.out.println(isChild(p1, p2));
    System.out.println(isChild(p2, p1));

    Path p3 = Paths.get("D:/Views/me/a.b");
    Path p4 = Paths.get("D:/Views/me/a.b/x/y");
    System.out.println(isChild(p3, p4));
    System.out.println(isChild(p4, p3));
}

//Check if childCandidate is child of path
public static boolean isChild(Path path, Path childCandidate) {
    return childCandidate.startsWith(path);
}

根据您的需要,您可以考虑在检查前在路径上使用toAbsolutePath()或toRealPath()。

以下是Path Operations的官方Java教程。

答案 1 :(得分:1)

尝试使用String的beginWith api:

String str1 = "D:/Views/me/a.b";
String str2 = "D:/Views/me/a";
if (str1.startsWith(str2 + ".") || str1.startsWith(str2 + "/")) {
    System.out.println("Yes it is");
}
str1 = "D:/Views/me/a/c/d";
str2 = "D:/Views/me/a";
if (str1.startsWith(str2 + ".") || str1.startsWith(str2 + "/")) {
     System.out.println("Yes it is");
}
Output:
Yes it is
Yes it is

答案 2 :(得分:1)

    String path = "D:/Views/me/a.b";
    String path2 = "D:/Views/me/a";
    File file = new File(path);
    if(file.getParentFile().getAbsolutePath().equals("path2")){
    System.out.println("file is parent");
    }else{
        System.out.println("file is not parent");
    }

答案 3 :(得分:0)

令人惊讶的是,没有简单但实用的解决方案。

以下是仅使用 java.nio.file.Path API的一种:

static boolean isChildPath(Path parent, Path child){
      Path pn = parent.normalize();
      Path cn = child.normalize();
      return cn.getNameCount() > pn.getNameCount() && cn.startsWith(pn);
}

测试用例:

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