56

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?

10 Answers 10

47

In Java 7 i do it like this:

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

Docs

5
  • 10
    The doc only mentions files. Does it work for directories ? Does it work on network paths ?
    – Zzirconium
    Jun 23, 2017 at 6:16
  • 3
    The argument is a Path so it should not matter wheter it is a File or Directory. Nov 27, 2017 at 13:12
  • 4
    This checks if a File is writable, but returns false if the file does not exist. So this will not work for this use case; if you do successfully write a file, then the .isWritable() check becomes sort of redundant.
    – kingledion
    Dec 31, 2018 at 16:56
  • 2
    It will not work if the file under path does not exist, documentation does not mention directories at all
    – maslan
    Mar 30, 2020 at 11:39
  • 1
    From a *nix perspective: directories are also just files...
    – gkhaos
    Mar 18, 2021 at 11:06
43

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()

4
  • f.canWrite fails in network path for example:- "\\abc123\canwrite". If i dont have the permission to write in this directory its not returning me the correct value.
    – amod
    Jan 10, 2013 at 10:07
  • 11
    This isn't the correct answer. Check the solution from Robert Niestroj
    – Asu
    Jul 9, 2018 at 16:20
  • @Asu Why it is not correct? I know that Files API is newer, but should not file.canWrite and Files.isWritable return same result?
    – Wortig
    May 16, 2023 at 11:38
  • 1
    @Wortig It has been a while since I had looked at it, but from what I can remember, this method just wasn't always reliable (sometimes it gives a wrong response).
    – Asu
    May 16, 2023 at 15:13
12

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.

2
  • Always i have exception java.security.AccessControlException: access denied, i create my owner directory/file with all permission
    – يعقوب
    Apr 21, 2021 at 8:43
  • AccessController is deprecated and marked for removal
    – Wortig
    May 17, 2023 at 9:33
7

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

This seems to work fine:

assertFalse(Files.isWritable(new File("/etc/").toPath()));
assertTrue(Files.isWritable(new File("/tmp/").toPath()));
0

Do you want to check permissions for folder or for files in folder?

"/*" in path name means a directory and all the files contained in that directory.

see javadoc

0

java.io.File has two methods canRead and canWrite that should suffice.

0
if(DocumentFile.fromFile(file).canWrite()){
   //allowed
   ...
}else{
   ...
}
0

On Windows, File.canWrite() does not always provide an accurate result. I would recommand using the following:

import java.nio.file.Files;
import java.nio.file.Paths;
...

if(Files.isWritable(Paths.get("path"))){
  //ok, write
}
0

Oops, one more thing. The directory also has to be executable, at least on linux:

  /** Make sure output dir exists and is writeable. */
  public boolean validateOutputDir(Path publishDirectory, Formatter error) {
    if (!Files.exists(publishDirectory)) {
      error.format(" Output directory '%s' does not exist%n", publishDirectory);
      return false;
    }
    if (!Files.isDirectory(publishDirectory)) {
      error.format(" Output directory '%s' is not a directory%n", publishDirectory);
      return false;
    }
    if (!Files.isWritable(publishDirectory)) {
      error.format(" Output directory '%s' is not writeable%n", publishDirectory);
      return false;
    }
    if (!Files.isExecutable(publishDirectory)) {
      error.format(" Output directory '%s' is not executable%n", publishDirectory);
      return false;
    }
    return true;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.