DirectoryStream与PathMatcher没有返回任何路径 [英] DirectoryStream with PathMatcher not returning any paths

查看:172
本文介绍了DirectoryStream与PathMatcher没有返回任何路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我已经看到很多类似问题的答案,但我无法使下面的代码工作,因为我认为应该:

Although I've seen a lot of answers for similar questions I can't make the following code work as I think it should:

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。

I expected to get a list of paths to all "somefile.xml" under C:\User\user_id and all subdirectories below that. Yet the hasNext() method returns false every time.

推荐答案

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

DirectoryStream only iterates through the directory you give it and matches entries in that directory. It does not look in any sub-directories.

您需要使用 Files <的一个walkXXXX方法/ code>查看所有目录。例如:

You need to use one of the walkXXXX methods of Files to look in all directories. For example:

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

这篇关于DirectoryStream与PathMatcher没有返回任何路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆