S-K'
S-K'

Reputation: 3209

Add all files recursively from root with Java 8 Stream

I have the following recursive method that simply adds all the child items in a given folder to a list:

private List<TemplateFile> readTemplateFiles(String nextTemplateDir, String rootTemplateDir) throws FileNotFoundException {
    List<TemplateFile> templateFiles = new ArrayList<>();

    for (File file : new File(nextTemplateDir).listFiles()) {
        if (!file.isDirectory() && !file.getName().startsWith(".")) {
            templateFiles.add(TemplateFile.create(file, rootTemplateDir));
        } else if (file.isDirectory()) {
            templateFiles.addAll(readTemplateFiles(file.getAbsolutePath(), rootTemplateDir));
        }
    }

    return templateFiles;
}

How could I refactor this method using the new Java 8 Stream API?

Upvotes: 5

Views: 672

Answers (1)

Tunaki
Tunaki

Reputation: 137229

You could use Files.walk(start, options...) to walk through a file tree recursively. This method returns a Stream<Path> consisting of all the Path starting from the given root.

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

private List<TemplateFile> readTemplateFiles(String nextTemplateDir, String rootTemplateDir) throws FileNotFoundException {
    return Files.walk(Paths.get(nextTemplateDir))
                .filter(path -> !path.getFileName().startsWith("."))
                .map(path -> TemplateFile.create(path.toFile(), rootTemplateDir))
                .collect(Collectors.toList());
}

Among the options, there is FOLLOW_LINKS that will follow symbolic links.

Upvotes: 5

Related Questions