问题
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