Create Directories with File permissions - Java

350 views Asked by At

I'm trying to create Directories locally with specific permissions, but it doesn't work in some cases and reverts to specific permissions.

This is my code

Path path = Paths.get(dir);
            
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrw-rw-");
            System.out.println("Permissions are " + PosixFilePermissions.asFileAttribute(perms).value());
            Files.createDirectories(path, PosixFilePermissions.asFileAttribute(perms));

The directory created reverts to the default permissions

 drwxr--r--    3 user  staff     96 Apr 18 18:16 testing

My umask was 022, I changed it to 000, but it still makes no difference when I create a directory from my application. There is a difference as long as I create it directly on the Terminal.

It works in specific cases, as long as I don't provide write access to the group and everyone else. What am I doing wrong?

1

There are 1 answers

2
Stan On

Ok, I might have figured it out with other answers on here.

If I run mkdir 755 testing, the permissions are still

drwxr-xr-x 2 user staff 64 Apr 18 19:10 testing

This is because my umask is 022

This impacts any file or directory created in a Unix based OS.

To fix this programmatically, I'm iterating over my directories until the user home and setting the permissions after creation

        Files.createDirectories(Paths.get(dir));
        Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrw-rw-");
        while(!path.toAbsolutePath().equals(Paths.get(System.getProperty("user.home")))) {
            Files.setPosixFilePermissions(path, perms);
            path = path.getParent();
        }