首页 > 解决方案 > AccessDeniedException 如果使用 Files.find()

问题描述

我需要在目录中找到所有匹配文件并获取一些信息(例如 unix 权限)。

如果我尝试使用 Files.find() 方法,它可以工作,但是有些文件或目录会导致 AccessDeniedException

例如

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) {}
    });
}

返回 :

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 

但是对相同的文件使用 Process 和 command 没有任何例外

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);
}

返回:

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

Process finished with exit code 0

使用 Files.find() 时出现异常的原因是什么?我不更改文件,不移动,只是获取一些属性信息

标签: javaunixjava-8streamaccess-denied

解决方案


我知道问题是什么。当我使用该过程时,我只获得了目录属性并没有进入它。但是在带有文件的示例中,我不仅获取目录还尝试进入,因为 maxdepth 设置为 1。需要将 maxdepth 设置为 0 以仅检查此目录而不进入。


推荐阅读