首页 > 解决方案 > Java 8 中评估 /path/a 是否是 /path 的子目录的正确方法是什么?

问题描述

几乎是标题所要求的。

假设我通过了“/tmp/foo/bar”的路径,并且我想特别确保该路径是路径“/tmp”的子目录,那么最“Java 8”的方式是什么? ?

具体来说,我有兴趣询问“给定两个独立的路径,/foo 和 /foo/bar/baz 我如何在不递归目录树的情况下测试 /foo/bar/baz 是否是 /foo 的子目录?” 我对探索 /foo 下的所有子目录并在下游查找 /foo/bar/baz 不感兴趣。

我一直在玩这个想法

@Test
public void test() {
    final Path root = Paths.get("/tmp");
    final Path path0 = Paths.get("/");
    final Path path1 = Paths.get("/opt/location/sub");
    final Path path2 = Paths.get("/tmp/location/sub");

    final Pattern ptrn = Pattern.compile("^[a-zA-Z].*$");

    final Function<Path, String> f = p -> root.relativize(p).toString();

    Assert.assertFalse("root",ptrn.matcher(f.apply(root)).matches());
    Assert.assertFalse("path0",ptrn.matcher(f.apply(path0)).matches());
    Assert.assertFalse("path1",ptrn.matcher(f.apply(path1)).matches());
    Assert.assertTrue("path2",ptrn.matcher(f.apply(path2)).matches());
}

但这感觉就像我一直工作到 Java 8 的边缘,然后又回到旧模式并错过了机会。

标签: javajava-8streamsubdirectory

解决方案


boolean startsWith(Path other)

测试此路径是否以给定路径开头。


推荐阅读