java - Java 8:列出来自多个路径的文件
问题描述
如何在 Java 8 中从多个路径搜索文件。这些不是子/兄弟目录。例如,如果我想在路径中搜索 json 文件,我有:
try (Stream<Path> stream = Files.find(Paths.get(path), Integer.MAX_VALUE, (p, attrs) -> attrs.isRegularFile() && p.toString().endsWith(".json"))) {
stream.map((p) -> p.name).forEach(System.out::println);
}
有没有更好的方法来搜索多个路径?还是我必须为多个路径运行相同的代码?
解决方案
是的,你可以做到。假设你有一个对象的路径List
,String
你可以这样做,
List<String> paths = ...;
paths.stream().map(path -> {
try (Stream<Path> stream = Files.list(Paths.get(path))) {
return stream.filter(p -> !p.toFile().isDirectory()).filter(p -> p.toString().endsWith(".json"))
.map(Path::toString).collect(Collectors.joining("\n"));
} catch (IOException e) {
// Log your ERROR here.
e.printStackTrace();
}
return "";
}).forEach(System.out::println);
如果您需要摆脱换行符,那么也可以这样做。
paths.stream().map(path -> {
try (Stream<Path> stream = Files.walk(Paths.get(path))) {
return stream.filter(p -> !p.toFile().isDirectory()).filter(p -> p.toString().endsWith(".json"))
.map(Path::toString).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return Collections.emptyList();
}).flatMap(List::stream).forEach(System.out::println);
在这里,您将.json
每个路径的所有文件名放入 a中,然后在打印之前List
将它们展平stream
为对象的平面。String
请注意,此方法中涉及的附加步骤是flatMap
.
推荐阅读
- sql - BigQuery SQL : Left Join with aggregate conditions
- python - Carriage return does not work with me correctly
- pytorch - AllenNLP DatasetReader.read 返回生成器而不是 AllennlpDataset
- swift - Xcode 12 and SVG from a string/text
- r - Using the grep command or another command for subsetting
- pandas - Associating arbitrary properties with cells in Pandas
- java - 使用 BFS 打印最短路径
- python - 找到 x 中大于 0.999 的第一个值的索引
- c# - 如何在 VS2015 中保存时禁用 Resharper 自动格式化
- python - 根据一列的排序对多个 Pandas Dataframe 列进行排序