I am trying to prepare a list of all files under /home/ dir.
Files.walk(Path.of("/home/"))
.filter(path -> !Files.isDirectory(path))
.filter(path -> {
try {
return !Files.isHidden(path);
} catch (IOException e) {
e.printStackTrace();
return false;
}
})
.filter(Files::isReadable)
.forEach(path -> print(path.toString()));
After printing a few files it this exception:
Exception in thread "main" java.io.UncheckedIOException: java.nio.file.AccessDeniedException: /home/vipin/.dbus
at java.base/java.nio.file.FileTreeIterator.fetchNextIfNeeded(FileTreeIterator.java:87)
at java.base/java.nio.file.FileTreeIterator.hasNext(FileTreeIterator.java:103)
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:132)
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at com.vip.Files.FIleHandling.main(FIleHandling.java:26)
Caused by: java.nio.file.AccessDeniedException: /home/vipin/.dbus
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:90)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
at java.base/sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:432)
at java.base/java.nio.file.Files.newDirectoryStream(Files.java:474)
at java.base/java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:300)
at java.base/java.nio.file.FileTreeWalker.next(FileTreeWalker.java:373)
at java.base/java.nio.file.FileTreeIterator.fetchNextIfNeeded(FileTreeIterator.java:83)
... 10 more
Process finished with exit code 1
The root cause of this Exception is sun.nio.fs.UnixException due to permission error.
We have a similar question on this.
My question is: How do we handle such cases when we don't have permission, is there any other API available to check permissions and filter on that?