gpt4 book ai didi

java - File.canRead() 返回 false

转载 作者:太空宇宙 更新时间:2023-11-04 09:29:56 51 4
gpt4 key购买 nike

我有一个服务器客户端程序,服务器运行在 Raspberry Pi(运行 Linux)上,客户端是一个 Android 应用程序。我正在编写一个应用程序文件浏览器,它只是将路径发送到服务器,然后服务器使用 file.listFiles()(服务器是用 Java 编写的)返回文件列表。

我以 sudo 运行服务器/Java 程序,希望这样可以访问系统中的所有文件,但令我惊讶的是,该用户没有 /的读取权限Pi 的 home 目录。

所以这是按顺序发生的事情:

我请求 file.listFiles(new File("/"));,它通过套接字从 Pi 发送到 Android 应用程序。在应用程序中,在发出下一个请求之前,我检查是否可以使用 file.canRead(); 读取文件,对于 /home 目录,这将返回 false。

Pi 上的文件权限:

pi@raspberrypi ~ $ ls -l / | grep home
drwxr-xr-x 3 root root 4096 Dec 31 1969 home

我如何运行 Java 服务器:

pi@raspberrypi ~ $ sudo java -cp "/usr/local/lib/bluecovelib/bluecove/target/bluecove-2.1.1-SNAPSHOT.jar:/usr/local/lib/bluecovelib/bluecove-gpl-2.1.1-SNAPSHOT/target/bluecove-gpl-2.1.1-SNAPSHOT.jar:/home/pi/severinteractionutils.jar:." AppConnect

为什么 sudo 用户无法从 Java 程序访问 /home 目录?

编辑:

我在 Pi 上运行了一个简单的程序来测试它是否是因为底层操作系统发生了变化。显然它确实有效果。

public class TestFileBrowser {
public static void main(String[] args) {
System.out.println("Hello, World");
File file = new File("/");
File [] files = file.listFiles();
for(int i=0; i<files.length; ++i) {
if(files[i].getAbsolutePath().equals("/home")) {
File homeDir = files[i];
if(homeDir.canRead()) {
System.out.println("Can Read");
if (homeDir.isDirectory()) {
System.out.println("Is directory");
}
}
}
}
}
}

这是控制台快照:

pi@raspberrypi ~ $ sudo javac TestFileBrowser.java 
pi@raspberrypi ~ $ sudo java TestFileBrowser
Hello, World
Can Read
Is directory

最佳答案

and for /home directory, this returns false.

正确,因为您无法使用典型的文件流 IO 从目录中读取。您可以调用File.isDirectory()其中(根据 Javadoc)

Tests whether the file denoted by this abstract pathname is a directory.

Where it is required to distinguish an I/O exception from the case that the file is not a directory, or where several attributes of the same file are required at the same time, then the Files.readAttributes method may be used.

并且您可以使用属性检查读取权限。

关于java - File.canRead() 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32643149/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com