Exception handling in Files.walk and Files.find
Steven Schlansker
stevenschlansker at gmail.com
Thu Jul 2 17:11:57 UTC 2015
How about BiConsumer<Path, IOException>, unless the Path is easily accessible otherwise?
On Jul 2, 2015, at 6:56 AM, Peter Levart <peter.levart at gmail.com> wrote:
> 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