How do I recursively list all files under a directory in Java? Does the framework provide any utility?
I saw a lot of hacky implementations. But none from the fra
The accepted answer is great, however it breaks down when you want to do IO inside the lambda.
Here is what you can do if your action declares IOExceptions.
You can treat the filtered stream as an Iterable, and then do your action in a regular for-each loop. This way, you don't have to handle exceptions inside a lambda.
try (Stream pathStream = Files.walk(Paths.get(path))
.filter(Files::isRegularFile)) {
for (Path file : (Iterable) pathStream::iterator) {
// something that throws IOException
Files.copy(file, System.out);
}
}
Found that trick here: https://stackoverflow.com/a/32668807/1207791