问题描述
虽然我已经看到很多类似问题的答案,但我无法使下面的代码工作,因为我认为应该:
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 查看所有目录。例如:
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没有返回任何路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!