Guillotine1789
Guillotine1789

Reputation: 342

Java.io.File.canRead() vs Java.nio.Files.isReadable() vs Java.io.FilePermission

What are the differences in those three to set or check if a file is readable/writable? I'm kind of lost between terms here..

What I need specifically is to open a file in a readable mode? Which one to choose? If the answer is nio.Files I'm using JVM 1.6 which does not include it, so how can i overcome then?

Upvotes: 1

Views: 1543

Answers (2)

user207421
user207421

Reputation: 310875

FilePermission is part of the Java security managar. If you're not using that, don't worry about it. The other two also test the permissions granted by the operating system, which is a completely different matter.

In 99% of cases you don't need any of them: just try to open the file and deal with the IOExceptions as they happen. That way you avoid timing window problems.

Upvotes: 1

jakub.petr
jakub.petr

Reputation: 3031

File.canRead uses FilePermission in its implementation. Files.isReadable is in Java NIO introduced in JDK 1.7, it has completely different implementation but should give the same result.

If you just need to check that you have the permission to read from a file use File.canRead but if you want to work with it then just open it and handle IOException (if the permission is denied or some other error occures).

Upvotes: 1

Related Questions