DirectoryStream with PathMatcher not returning any paths

ⅰ亾dé卋堺 提交于 2019-12-20 04:33:09

问题


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) {...

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.


回答1:


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

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()));
}


来源:https://stackoverflow.com/questions/37383668/directorystream-with-pathmatcher-not-returning-any-paths

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!