Search code examples
javapermissionsnio777

Write permissions not getting set when using NIO on unix


I am using NIO to set permissions on all directories in a path as below. i am trying to give 777 permissions , however the "w" part is not getting applied...Whats wrong here?

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

public class permissionTest {

    public static void main(String [] args) throws IOException{

        Path dirPath = Paths.get("./part1/part2/part3");


        Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx");
        System.out.print(permissions.toString() + ' ');

        FileAttribute<Set<PosixFilePermission>> fileAttributes = 

                PosixFilePermissions.asFileAttribute(permissions);

        Files.createDirectories(dirPath, fileAttributes);

    }

}

$ ls -ld part1/
drwxr-xr-x 3 * *4096 Oct 30 02:48 part1/

Solution

  • This is because the umask is applied.

    Try and type this at the shell:

    umask 0
    

    and then rerun your program (or launch your IDE from the command line and run the code). It also means that if you do umask 027, the permissions for your created directories will be 750.

    Unfortunately, you cannot change your process' umask (since this is per process, and inherited) in Java itself...


    Note that there is this method to set "absolute" file permissions.