Java 8: List files from multiple paths

Nik :

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?

Ravindra Ranwala :

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);

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473456&siteId=1