How to check write permissions of a directory in java?

I would like a code snippet that checks whether a directory has read/write permissions and do something if it does, and does something else if it doesnt. I tried an example shown here:

try {
    AccessController.checkPermission(new FilePermission("/tmp/*", "read,write"));
System.out.println("Good");
    // Has permission
} catch (SecurityException e) {
    // Does not have permission
System.out.println("Bad");
}

The problem is the exception is always triggered, so it always ends up printing "Bad" regardless of whether the directory has write permissions or not. (I chmod the directories to 777 or 000 to test).

Is there an alternative or some way to accomplish what I need?


In Java 7 i do it like this:

if(Files.isWritable(path)){
  //ok, write
}

Docs


if you just want to check if you can write:

File f = new File("path");
if(f.canWrite()) {
  // write access
} else {
  // no write access
}

for checking read access, there is a function canRead()


You should use the path of the directory alone ("/tmp") to query the permissions of a directory:

AccessController.checkPermission(new FilePermission("/tmp", "read,write"));

With "/tmp/*" you query the permissions of all files inside the /tmp directory.


Java has its own permission model revolving around the use of an AccessController and Permission classes. The permissions are granted to a code source (the location from where the classes are loaded), and in some/most cases these permissions are different from any underlying permissions required to access the desired resource.

For instance, although you may have granted all users to read and write to the /tmp directory, this isn't sufficient for the AccessController to grant your code the necessary permission. You'll also need to add a rule in the policy file used (by the AccessController) to read and write files from the /tmp directory. The rule to be created will be equivalent to the following:

grant codeBase "<location of the codebase>" {
    permission java.io.FilePermission "/tmp/-", "read, write";
};