Recursively Enumerating Files with Java
Exploring the options for recursively listing files under a specified directory, we uncover various approaches. While "hacky" implementations exist, the Java framework itself offers robust utilities to streamline this task.
Java 8's Streamlined Approach
Java 8 introduces a convenient stream-based solution:
try (Stream<Path> stream = Files.walk(Paths.get(path))) { stream.filter(Files::isRegularFile) .forEach(System.out::println); }
This approach provides an elegant way to traverse files and supports a range of stream operations like filtering, mapping, and limiting.
Files.find: Filtering on File Attributes
Java also provides Files.find, which accepts a bi-predicate to filter files based on attributes:
Files.find(Paths.get(path), Integer.MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile()) .forEach(System.out::println);
While Files.find may offer specific optimization when filtering on attributes, its performance is generally comparable to Files.walk.
Performance Comparison
When evaluating these approaches, we recommend considering the specific performance implications based on your usage scenario. For more detailed insights, refer to the GitHub project in the answer's update, which provides results and a test case.
The above is the detailed content of How Can Java Efficiently Recursively Enumerate Files?. For more information, please follow other related articles on the PHP Chinese website!