For those who are also interested in Java 7 and NIO, there is an alternative solution for @voo's answer above . We can use try-with-resources, which calls Files.find() and the lambda function, which is used to filter directories.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; final Path directory = Paths.get("/path/to/folder"); try (Stream<Path> paths = Files.find(directory, Integer.MAX_VALUE, (path, attributes) -> attributes.isDirectory())) { paths.forEach(System.out::println); } catch (IOException e) { ... }
We can even filter directories by name by changing the lambda function:
(path, attributes) -> attributes.isDirectory() && path.toString().contains("test")
or by date:
final long now = System.currentTimeMillis(); final long yesterday = new Date(now - 24 * 60 * 60 * 1000L).getTime();
HugoTeixeira Aug 01 '18 at 23:31 2018-08-01 23:31
source share