Search code examples
javaunixjava-8streamaccess-denied

AccessDeniedException if using Files.find()


I need to find all match files in directory and get some information (for example unix permissions).

If i try it with using Files.find() method it works, but there are some files or directories which cause an AccessDeniedException

for example

try (Stream<Path> stream = Files.find(Paths.get("/etc/cups/ssl"), 1, (p, bfa) -> true)) {
    stream.forEach(p -> {
    try {
        PosixFileAttributes attr = Files.readAttributes(p, PosixFileAttributes.class);
        System.out.println(attr.permissions());
    } catch (IOException e) {}
    });
}

return :

Exception in thread "main" java.nio.file.AccessDeniedException: /etc/cups/ssl
    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:428)
    at java.base/java.nio.file.Files.newDirectoryStream(Files.java:471)
    at java.base/java.nio.file.FileTreeWalker.visit(FileTreeWalker.java:300)
    at java.base/java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:322)
    at java.base/java.nio.file.FileTreeIterator.<init>(FileTreeIterator.java:71)
    at java.base/java.nio.file.Files.find(Files.java:3937)
    at unix.utils.UnixFile.main(UnixFile.java:2371)

 Process finished with exit code 1 

But using Process and command with the same files works without any exceptions

String[] command = { "/bin/sh", "-c", "/bin/ls -ldA /etc/cups/ssl" };
Process process = Runtime.getRuntime().exec(command);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
    System.out.println(line);
}

return:

drwx------ 2 root lp 4096 Feb 16 16:48 /etc/cups/ssl

Process finished with exit code 0

What's the reason of Exception when using Files.find()? I dont change files, dont move, just get some attributes information


Solution

  • I got what the problem is. when I used the process I only got the directory attributes and did not enter into it. But in the example with Files I not only get directoriy also try to go inside, cause maxdepth is set as 1. Need to set maxdepth into 0 to check only this directory without entering.