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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11901382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:51:05  来源:igfitidea点击:

How to check if a file is readable?

javawinapijava-native-interfacejna

提问by peter

I'm writing Java 6 application and I have to check if a file is readable. However, on Windows canRead()always returns true. So I see that probably, the only solution could be some native solution based on WINAPI and written in JNA/JNI.

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

But, there is another problem, because it's difficult to find a simple function in WINAPI which would return information about access to a file. I found GetNamedSecurityInfoor GetSecurityInfobut I'm not an advanced WINAPI programmer and they are too complicated for me in connection with JNA/JNI. Any ideas how to deal with this problem?

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

回答by Roman C

Try to use the following code

尝试使用以下代码

public boolean checkFileCanRead(File file){
    try {
        FileReader fileReader = new FileReader(file.getAbsolutePath());
        fileReader.read();
        fileReader.close();
    } catch (Exception e) {
        LOGGER.debug("Exception when checking if file could be read with message:"+e.getMessage(), e);
        return false;
    }
    return true;
}

回答by svarog

Java 7 introduced the Files.isReadablestatic method, it accepts a file Pathand returns true if file exists and is readable, otherwise false.

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

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.

测试文件是否可读。此方法检查文件是否存在以及此 Java 虚拟机是否具有允许它打开文件进行读取的适当权限。根据实现,此方法可能需要读取文件权限、访问控制列表或其他文件属性,以检查对文件的有效访问。因此,该方法对于其他文件系统操作可能不是原子的。

请注意,此方法的结果会立即过时,无法保证后续尝试打开文件进行读取会成功(或者甚至会访问同一个文件)。在安全敏感应用程序中使用此方法时应小心。

Example:

例子:

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

回答by aleroot

You could use FilePermissionand AccessControllertougher in this way :

您可以通过这种方式更严格地使用FilePermissionAccessController

FilePermission fp = new FilePermission("file.txt", "read");
AccessController.checkPermission(fp);

If a requested access is allowed, checkPermission returns quietly. If denied, an AccessControlException is thrown.

如果允许请求的访问,则 checkPermission 安静地返回。如果拒绝,则抛出 AccessControlException。

回答by user207421

You only need to know if it's readable if you are going to read it. So, just try to read it, when you need to, and deal with it if you can't. The best way to test the availability of any resource is just to try to use it and deal with the exceptions or errors as they arise. Don't try to predict the future.

如果你打算阅读它,你只需要知道它是否可读。所以,当你需要的时候,试着阅读它,如果你不能,就处理它。测试任何资源可用性的最佳方法就是尝试使用它并在出现异常或错误时对其进行处理。不要试图预测未来。

回答by riskop

It can be perfectly reasonable to check accessibility of a resource (readability of a file in this case) long before the actual usage of that resource.

在资源实际使用之前很久就检查资源的可访问性(在这种情况下是文件的可读性)是完全合理的。

Imagine a server application which will use a subcomponent which will read a particular file in some circumstances some time later. It can be useful to check the readability of the file at server startup and WARN if it's not readable. Then somebody can fix the situation (make the file readable, anything) before the circumstances actually causes the subcomponent to try to read that file.

想象一个服务器应用程序,它将使用一个子组件,该组件将在一段时间后的某些情况下读取特定文件。在服务器启动时检查文件的可读性很有用,如果不可读则发出 WARN。然后有人可以在情况实际导致子组件尝试读取该文件之前修复这种情况(使文件可读,任何事情)。

Of course, this upfront check is not a substitute for proper exception handling in the sub component (it's very possible that the file is readable at start but became unreadable later).

当然,这种预先检查并不能替代子组件中正确的异常处理(很可能文件在开始时可读但后来变得不可读)。

So the question about pre-checking is perfectly valid I think.

所以我认为关于预先检查的问题是完全有效的。

As for the method of checking the resource, try to do something as similar as possible to actual usage. If later the file will be read, then try to read it!

至于查看资源的方法,尽量做一些与实际使用类似的。如果稍后将读取该文件,则尝试读取它!

As for Files.isReadable(...): there's no guarantee that the file system provider beneath Files.isReadable(...) is not buggy. It can return true, and then throw an exception if the file is actually read.

至于 Files.isReadable(...):不能保证 Files.isReadable(...) 下的文件系统提供者没有问题。它可以返回true,然后在实际读取文件时抛出异常。

Of course, if you are writing a file manager application then use Files.isReadable(...), but I guess that is not the case.

当然,如果您正在编写文件管理器应用程序,请使用 Files.isReadable(...),但我想情况并非如此。