【问题标题】:DirectoryStream with PathMatcher not returning any paths带有 PathMatcher 的 DirectoryStream 不返回任何路径
【发布时间】:2016-05-23 06:10:25
【问题描述】:

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

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() 方法每次都返回 false。

【问题讨论】:

    标签: java file wildcard


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 只是有点不同(此处仅限于 Java 7),但这确实解决了我的问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    相关资源
    最近更新 更多