When running Files.walk(Paths.get(\"/var/\")).count()
as an unprivileged user, the execution might throw an exception as there are folders inside /var/
If what you want is actually skipping the paths where you have no access, you have two approaches:
Streams
In the answer to this question it is explained how to obtain the stream of all files of a subtree you can access.
But this example can be expanded to other use cases too.
FileVisitor
Using a FileVisitor
adds a lot of code, but grants you much more flexibility when walking directory trees. To solve the same problem you can replace Files.walk()
with:
Files.walkFileTree(Path start, FileVisitor super Path> visitor);
extending SimpleFileVisitor (to count the files) and overriding some methods.
You can:
visitFileFailed
method, to handle the case you cannot access a file for some reasons; (Lukasz_Plawny's advice)preVisitDirectory
method, checking for permissions before accessing the directory: if you can't access it, you can simply skip its subtree (keep in mind that you may be able to access a directory, but not all its files);e.g. 1
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
// you can log the exception 'exc'
return FileVisitResult.SKIP_SUBTREE;
}
e.g. 2
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if(!Files.isReadable(dir))
return FileVisitResult.SKIP_SUBTREE;
return FileVisitResult.CONTINUE;
}
FileVisitor docs
FileVisitor tutorial
Hope it helps.