Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file is readable?

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.

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 GetNamedSecurityInfo or GetSecurityInfo but 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?

like image 956
peter Avatar asked Aug 10 '12 12:08

peter


People also ask

How can I tell if a file is readable?

You can check the file properties by right-clicking on the file and choosing Properties. If the Read-only attribute is checked, you can uncheck it and click OK.

How do you check if a file exists and is readable in bash?

To check if the a file is readable, in other words if the file has read permissions, using bash scripting, use [ -r FILE ] expression with bash if statement.

How do you know if a file is writable?

test -r file. txt -a -w file. txt echo $? The return code is 0 if it is both readable and writeable.

How do I know if a python file is readable?

The readable() method returns True if the file is readable, False if not.


2 Answers

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
like image 196
svarog Avatar answered Sep 23 '22 17:09

svarog


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;
}
like image 32
Roman C Avatar answered Sep 21 '22 17:09

Roman C