Video in progress
How do you list the files in a directory? What is the difference between Files.list and Files.walk?
Files.list(dir) gives only the first-level entries, while Files.walk(dir) descends recursively into all subdirectories. Both return a Stream<Path> and hold an open directory handle, so they are closed with try-with-resources.
📖 Answer
Path dir = Path.of("reports");
try (Stream<Path> s = Files.list(dir)) {
s.filter(Files::isRegularFile).forEach(System.out::println);
}
try (Stream<Path> s = Files.walk(dir, 3)) { // up to 3 levels
List<Path> pdfs = s.filter(p -> p.toString().endsWith(".pdf")).toList();
}
For a more complex filter (size, modification time) Files.find is handy: it gives you the attributes without extra calls.
A common mistake is not closing the stream. You won't notice it in a single call, but in a scheduled job that runs every minute, "Too many open files" shows up after a few days.
Files.walk does not follow symlinks by default. If you pass FileVisitOption.FOLLOW_LINKS it does, but then loops can appear.
Sign up to mark studied questions and save your progress.