虽然我已经看到了很多类似问题的答案,但我不能让下面的代码像我认为的那样工作:
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下所有“C:\User\user_id”以及下面所有子目录的路径列表。然而,hasNext()方法每次都返回false。
发布于 2016-05-23 07:24:06
DirectoryStream只遍历给它的目录,并匹配该目录中的条目。它做的是而不是在任何子目录中查找。
您需要使用walkXXXX的Files方法之一来查看所有目录。例如:
try (Stream<Path> stream = Files.walk(dataDir.toPath())) {
stream.filter(pathMatcher::matches)
.forEach(path -> System.out.println(path.toString()));
}注意:Stream由Files.walk返回(以及Files中的其他几种方法),必须关闭,否则资源将泄漏。建议使用如下图所示的try-with语句。
https://stackoverflow.com/questions/37383668
复制相似问题