How to check if a file is readable?

前端 未结 5 2219
滥情空心
滥情空心 2020-12-15 11:50

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 probabl

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 12:44

    Java 7 introduced the Files.isReadable static method, it accepts a file Path and returns true if file exists and is readable, otherwise 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.

    Example:

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

提交回复
热议问题