java - 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 的边缘,然后又回到旧模式并错过了机会。
解决方案
boolean startsWith(Path other)
测试此路径是否以给定路径开头。
推荐阅读
- html - 模板 CSS 插入覆盖主要 CSS
- python - 如何将带有 dict 的字符串转换为实际的 dict 对象?
- c# - 如何从 asp.net 核心中的一个控制器操作调用 2 个 API?
- python - 由一个进程更改并影响其他进程的全局布尔值
- python - 如何在后台使用pyautogui脚本
- arduino - Arduino从串行读取给出了不需要的输入
- php - PHP工匠迁移异常
- go - chromedp 得到无效的 CSRF 令牌错误;Puppeteer 和浏览器都可以
- html - 在表单操作中指定动态 url
- postgresql - 如何使用 Postgrex 在 Amazon Redshift 上执行的 SELECT 语句的结果填充本地 Postgres 表?