如何在 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);
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法在多个路径中搜索?或者我是否必须为多个路径运行相同的代码?
是的,你可以做到。假设你有作为对象的路径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);
Run Code Online (Sandbox Code Playgroud)
如果您需要删除换行符,也可以这样做。
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);
Run Code Online (Sandbox Code Playgroud)
在这里,您将.json每个路径的所有文件名放入一个List,然后在打印之前将它们拼合成一个对象stream平面String。请注意,此方法涉及的附加步骤是flatMap。
| 归档时间: |
|
| 查看次数: |
3175 次 |
| 最近记录: |