Add all files recursively from the root using Java 8 Stream

I have the following recursive method, which simply adds all the children to the given folder in the 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 can I reorganize this method using the new Java 8 Stream API?

+5
source share
1 answer

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

Return a Stream , which is lazily populated by Path , going through the file tree embedded in the given initial file. The file tree goes first in depth, the elements in the stream are Path objects, which are obtained as if by resolving the relative path from 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 parameters there is FOLLOW_LINKS which will follow symbolic links.

+5
source

Source: https://habr.com/ru/post/1239767/


All Articles