java - 如何检查文件是否可读?

标签 java winapi java-native-interface jna

我正在编写 Java 6 应用程序,我必须检查文件是否可读。但是,在 Windows 上,canRead() 始终返回 true。所以我认为,唯一的解决方案可能是一些基于 WINAPI 并用 JNA/JNI 编写的 native 解决方案。

但是,还有另一个问题,因为很难在 WINAPI 中找到一个简单的函数来返回有关文件访问的信息。我找到了 GetNamedSecurityInfoGetSecurityInfo 但我不是高级 WINAPI 程序员,它们对我来说与 JNA/JNI 相关太复杂了。任何想法如何处理这个问题?

最佳答案

Java 7 引入了Files.isReadable 静态方法,它接受一个文件Path。如果文件存在且可读,则返回 true,否则返回 false。

From the docs

Tests whether a file is readable. This method checks that a file exists and that this Java virtual machine has appropriate privileges that would allow it open the file for reading. Depending on the implementation, this method may require to read file permissions, access control lists, or other file attributes in order to check the effective access to the file. Consequently, this method may not be atomic with respect to other file system operations.

Note that the result of this method is immediately outdated, there is no guarantee that a subsequent attempt to open the file for reading will succeed (or even that it will access the same file). Care should be taken when using this method in security sensitive applications.

例子:

File file = new File("/path/to/file");
Files.isReadable(file.toPath()); // true if `/path/to/file` is readable

关于java - 如何检查文件是否可读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11901382/

相关文章:

java - 来自 ejb.jar 问题的 Glassfish 3.1.2 lib/jar 引用

java - 推荐一本不错的JNI书

python - 我可以阻止可执行文件请求 UAC 提升吗?

android - Android JNI中的高精度定时器

android - 在 Android Studio 中使用预构建库和 jni

java - 使用 String.matches() 代替 util Pattern 匹配前两位数字

java - 无法将 JTextField 设置为 int

java - 不要在 jsoup 中显示另一个标签内的标签

c++ - 添加对在基于对话框的 MFC 应用程序中打印和预览 HTML 的支持

c# - 如何捕获屏幕的一部分