How to check if a file is readable?

peter picture peter · Aug 10, 2012 · Viewed 21.2k times · Source

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?

Answer

Roman C picture Roman C · Aug 10, 2012

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;
}