java - 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() 时出现异常的原因是什么?我不更改文件,不移动,只是获取一些属性信息
解决方案
我知道问题是什么。当我使用该过程时,我只获得了目录属性并没有进入它。但是在带有文件的示例中,我不仅获取目录还尝试进入,因为 maxdepth 设置为 1。需要将 maxdepth 设置为 0 以仅检查此目录而不进入。
推荐阅读
- python - 在句子中搜索单词
- laravel - Laravel 路由问题。例如:“admin”和“admin/”
- firebase - 从 Firebase 结果构建未来
- angular - 使用 Karma Angular 而不是开玩笑的快照测试
- python - 删除字符/空格直到第一个选择的字符python
- ipfs - 无法运行 ipfs 守护进程
- liquid - Azure APIM | Liquid 模板 - 无需集成帐户即可将 JSON 转换为 XML
- xml - 除了匹配的内部元素之外,xpath 还可以抓取外部元素
- ios - 标题部分视图 UITableView 中的标签和按钮
- c# - EMGU.CV 两幅图像的相似度百分比