Exception handling in Files.walk and Files.find
Peter Levart
peter.levart at gmail.com
Thu Jul 2 13:56:03 UTC 2015
Hi,
Recently I wanted to use Files.walk method returning a Stream<Path> to
scan a directory of files. I quickly learned that it is of limited use.
For example, the following code:
long pngFilesCount = Files.walk(Paths.get("/usr"))
.filter(path -> path.toString().endsWith(".png"))
.count();
Throws exception on my computer:
Exception in thread "main" java.io.UncheckedIOException:
java.nio.file.AccessDeniedException: /usr/share/polkit-1/rules.d
This is a consequence of the fact that some files and/or directories in
the tree being scanned are not accessible to my user account on the
computer. If I wanted to skip those files/directories I would be forced
to use different API (Files.walkFileTree using FileVisitor which can
handle exceptions too).
I propose the addition of overloads to Files.walk and Files.find that
take an additional parameter of type Consumer<IOException> to be
responsible for handling IOExceptions that are thrown while walking the
file tree:
http://cr.openjdk.java.net/~plevart/jdk9-dev/Files.walkIOException/webrev.01/
Ignoring AccessDeniedException(s) in above code can therefore be coded as:
long pngFilesCount = Files.walk(Paths.get("/usr"),
Integer.MAX_VALUE,
ioe -> {
if (!(ioe instanceof AccessDeniedException)) {
throw new UncheckedIOException(ioe);
}
})
.filter(path -> path.toString().endsWith(".png"))
.count();
What do you think?
Regards, Peter
More information about the core-libs-dev
mailing list