我正在编写 Java 6 应用程序,我必须检查文件是否可读。但是,在 Windows 上,canRead()
始终返回 true
。所以我认为,唯一的解决方案可能是一些基于 WINAPI 并用 JNA/JNI 编写的 native 解决方案。
但是,还有另一个问题,因为很难在 WINAPI 中找到一个简单的函数来返回有关文件访问的信息。我找到了 GetNamedSecurityInfo
或 GetSecurityInfo
但我不是高级 WINAPI 程序员,它们对我来说与 JNA/JNI 相关太复杂了。任何想法如何处理这个问题?
最佳答案
Java 7 引入了Files.isReadable
静态方法,它接受一个文件Path
。如果文件存在且可读,则返回 true,否则返回 false。
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/