Exception catching in lambda expressions

I have the simplest code using Files.walk:

Stream<Path> stream = Files.walk(Paths.get("C:\\"));
stream.forEach(f -> {
    System.out.println(f);
});

This code throws

Exception in thread "main" java.io.UncheckedIOException: java.nio.file.AccessDeniedException: C:\Documents and Settings
    at java.nio.file.FileTreeIterator.fetchNextIfNeeded(Unknown Source)
    at java.nio.file.FileTreeIterator.hasNext(Unknown Source)
    at java.util.Iterator.forEachRemaining(Unknown Source)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining (Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown 
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential (Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    at devl.test.FindDuplicates.main(FindDuplicates.java:53)
Caused by: java.nio.file.AccessDeniedException: C:\Documents and Settings
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsDirectoryStream.<init>(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream (Unknown Source)
    at java.nio.file.Files.newDirectoryStream(Unknown Source)
    at java.nio.file.FileTreeWalker.visit(Unknown Source)
    at java.nio.file.FileTreeWalker.next(Unknown Source)
    ... 11 more

And the stacktrace pointer points to stream.forEach(f -> {. Adding try / catch before the code causes it to stop reading files when an exception is thrown.

The thing is, I want the code to continue to read different files on the C drive, despite the fact that this is an exception.

It seems that somehow adding try / catch inside the foreach will solve it - how to do it (try / catch on f -> {, not System.out.println(f);)?

Please note that I tried to get around this by doing

Stream<Path> s = stream.filter(f -> !f.toFile().getAbsolutePath().contains("Documents and Setting"));   
s.forEach(f -> {

But the same exception is thrown (even the execution stream.filter(f -> false)fails).

: , ( ). , s.forEach(LambdaExceptionUtil.rethrowConsumer(System.out::println)) - .

+4
2

, walkFileTree FileVisitor, .

(walk) , , .

+4
0

Source: https://habr.com/ru/post/1666828/


All Articles