带有 PathMatcher 的 DirectoryStream 不返回任何路径

DirectoryStream with PathMatcher not returning any paths

尽管我已经看到很多类似问题的答案,但我无法使以下代码按我认为的方式工作:

File dataDir = new File("C:\User\user_id");
PathMatcher pathMatcher = FileSystems.getDefault()
    .getPathMatcher("glob:" + "**\somefile.xml");
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(
    dataDir.toPath(), pathMatcher::matches)) {
    Iterator<Path> itStream = dirStream.iterator();
    while(itStream.hasNext()) {
        Path resultPath = itStream.next();
    }
} catch (IOException e) {...

我希望获得 C:\User\user_id 下所有 "somefile.xml" 及其下所有子目录的路径列表。然而 hasNext() 方法 returns 每次都是错误的。

DirectoryStream 仅遍历您提供的目录并匹配该目录中的条目。它不会查看任何子目录。

您需要使用 Files 的 walkXXXX 方法之一来查看所有目录。例如:

try (Stream<Path> stream = Files.walk(dataDir.toPath())) {
  stream.filter(pathMatcher::matches)
        .forEach(path -> System.out.println(path.toString()));
}

注意:Files.walk返回的Stream(以及Files中的其他几个方法)必须关闭,否则会泄露资源.建议使用此处所示的 try-with-resources 语句。