如何根据以前的过滤结果简化流搜索?
HashMap<Boolean, List<Path>> result = (HashMap<Boolean, List<Path>>) Files.walk(Paths.get(folder)).map(Path
::toAbsolutePath).collect(Collectors.groupingBy(Files::isSymbolicLink));
result.get(true).stream().filter(path -> {
try {
return !result.get(false).contains(Files.readSymbolicLink(path));
} catch (IOException e) {
throw Throwables.propagate(e);
}
}).forEach(symbolicLink -> {
try {
result.get(false).addAll(Files.walk(symbolicLink, FileVisitOption.FOLLOW_LINKS).collect(Collectors
.toList()));
} catch (IOException e) {
throw Throwables.propagate(e);
}
});
return result.get(false).stream().filter(Files::isRegularFile).distinct().collect(Collectors.toList());
您可以通过将一些代码提取到方法中并避免使用来进行整理HashMap
。
HashMap
您可以将文件存储在而不是中Set<Path>
。这将强制执行唯一性,因此您实际上无需费心检查符号链接是否指向您已经拥有的文件,并且可以删除一些过滤:
public Set<Path> getAllFiles(final String folder) throws IOException {
return Files.walk(Paths.get(folder))
.map(Path::toAbsolutePath)
.flatMap(this::getAllFiles)
.collect(Collectors.toSet());
}
private Stream<Path> getAllFiles(final Path path) {
if(!Files.isSymbolicLink(path)) return Stream.of(path);
try {
return Files.walk(path, FileVisitOption.FOLLOW_LINKS)
.filter(Files::isRegularFile);
} catch (IOException e) {
e.printStackTrace();
}
return Stream.empty();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句