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?
Streams, introduced in Java 8, use functional-style operations to process data declaratively. The elements of streams are consumed from data sources such as collections, arrays, or I/O resources like files. In this article, we’ll explore the various possibilities of using streams to make life easier when it comes to the handling of files.
Using Java 8 Java 8 introduced a method walk () in Files class. 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.
Java 8 – List of All Files in a Directory Learn to use Java 8 APIs such as Files.list () and DirectoryStream to list all files present in a directory, including hidden files, recursively. For using external iteration (for loop) use DirectoryStream. For using Stream API operations (map, filter, sorted, collect), use Files.list () instead.
Files.list () – Iterate over all files and sub-directories Java example to iterate over a directory and get the List<File> using Files.list () method. 2. Files.list () – List only files excluding sub-directories Use the filter expression Files::isRegularFile to check if a file is normal file, and not any directory.
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 withPath
by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream arePath
objects that are obtained as if by resolving the relative path againststart
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With