Create directory with write permissions for the group

前端 未结 5 1334
时光说笑
时光说笑 2021-01-11 11:44

I create a folder in my java program (running on linux) with mkdirs() function of File object. The problem is that the folder gets only read permissions for the group. I nee

相关标签:
5条回答
  • 2021-01-11 12:17

    OK this is not a java solution and definitely not portable.

    Since you mention that you are linux, probably you can think of checking the "umask" settings and setting it appropriately (to have directories created with group write permissions) and then launching your java program.

    0 讨论(0)
  • 2021-01-11 12:18

    A very simple solution for this is:

    file.setExecutable(true, false);
    file.setReadable(true, false);
    file.setWritable(true, false);
    

    In above code, file is a File object.

    When you are creating a file set these permissions to a file setExecutable(true) will allow you to set that file as Executable for owner only. If you add one more parameter which I have added in above code file.setExecutable(true, false); will make Executable false for owner only, that means it will set permissions to all group / world.

    Tested and working on Debian and Windows XP.

    0 讨论(0)
  • 2021-01-11 12:22

    Java nio can help with posix file attributes: https://docs.oracle.com/javase/8/docs/api/java/nio/file/attribute/PosixFileAttributeView.html

    Path path = ...
     Set<PosixFilePermission> perms =
         EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_WRITE);
     Files.createFile(path, PosixFilePermissions.asFileAttribute(perms));
    
    0 讨论(0)
  • 2021-01-11 12:33

    I suspect (unless/until someone posts an answer to the contrary) that there's no way to do this in Java's standard library, because POSIX group permissions (the rwxrwxrwx kind you're used to) are not cross-platform. Java 6 will let you set owner permissions or global permissions, but (as far as I can tell) not group permissions. If you really must do it, try using Runtime.exec("chmod g+w directory"), but it might be a good idea stylistically to wrap it in a method like setGroupWritable().

    0 讨论(0)
  • 2021-01-11 12:41

    On java 6, there are methods that allow you to do this, like setwriteable(). On previous versions of java, you'll have to access the command line to do a chmod command.

    Java 6 SE File Class Doc.

    EDIT: Woops, I'm completely wrong; I failed to notice that you wanted group permissions specifically. Those don't appear to be settable without Runtime.exec().

    @David: You're right.

    Another thought: if you have a lot of files to change, how about writing a shell script and calling that from runtime.exec()?

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