Java 8:列出来自多个路径的文件 [英] Java 8: List files from multiple paths
问题描述
如何在Java 8中从多个路径搜索文件.这些不是子目录或兄弟目录.例如,如果我想在路径中搜索json文件,则可以:
How to search files from multiple paths in Java 8. These are not sub/sibling directories. For example, if I want to search json files in a path, I have:
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);
}
是否有更好的方法来搜索多个路径?还是我必须针对多个路径运行相同的代码?
Is there a better way to search in multiple paths? Or do I have to run the same code for multiple paths?
推荐答案
是的,您可以这样做.假设您具有作为 String
对象的 List
的路径,则可以这样做,
Yes you can do it. Assuming you have paths as a List
of String
objects, you can do it like so,
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);
如果您需要摆脱换行符,也可以这样做.
In case if you need to get rid of the new-line character, then it can be done like this too.
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
文件名放入 List
,然后将它们展平为 String
对象,然后再打印.请注意,此方法涉及的另一个步骤是 flatMap
.
Here you get all the .json
file names for each path into a List
, and then flatten them into a flat stream
of String
objects before printing. Notice that the additional step involved in this approach which is flatMap
.
这篇关于Java 8:列出来自多个路径的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!