Exception handling in Files.walk and Files.find
Peter Levart
peter.levart at gmail.com
Fri Jul 3 08:25:02 UTC 2015
Hi Steven,
I thought of that too. Yes, it can even be a BiPredicate<Path, IOException>:
http://cr.openjdk.java.net/~plevart/jdk9-dev/Files.walkIOException/webrev.02/
If one of the proposed APIs is acceptable, I can push this further and
add required test(s), etc...
Regards, Peter
On 07/02/2015 07:11 PM, Steven Schlansker wrote:
> 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