How to check if a file is readable?

Viewed 24709

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?

5 Answers

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.

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.

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

Related