How to check write permissions of a directory in java?

后端 未结 8 1753
粉色の甜心
粉色の甜心 2020-12-29 01:13

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

相关标签:
8条回答
  • 2020-12-29 01:48
    if(DocumentFile.fromFile(file).canWrite()){
       //allowed
       ...
    }else{
       ...
    }
    
    0 讨论(0)
  • 2020-12-29 01:49

    In Java 7 i do it like this:

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

    Docs

    0 讨论(0)
  • 2020-12-29 01:49

    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 讨论(0)
  • 2020-12-29 01:55

    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";
    };
    
    0 讨论(0)
  • 2020-12-29 01:57

    This seems to work fine:

    assertFalse(Files.isWritable(new File("/etc/").toPath()));
    assertTrue(Files.isWritable(new File("/tmp/").toPath()));
    
    0 讨论(0)
  • 2020-12-29 01:59

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

    0 讨论(0)
提交回复
热议问题