Java - Updating POSIX file permissions

Introduction

To update POSIX file permissions, get all permissions in a Set of PosixFilePermission enum constants.

Call the setPermissions() method of PosixFileAttributeView, passing the Set of the PosixFilePermission enum constants as an argument.

The following code shows how to set the POSIX file permissions:

// Get the permission in a string form
String rwxFormPermissions = "rw-r-----";

// Convert the permission in the string form to a Set of PosixFilePermission
Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(rwxFormPermissions);

// Update the permissions
posixView.setPermissions(permissions);

Or you can create a Set of PosixFilePermission enum constants directly and set it as the file permissions

Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ, OWNER_WRITE, GROUP_READ);
posixView.setPermissions(permissions);

The following code reads and updates POSIX file permissions for a file named test on UNIX-like platforms.

Demo

import static java.nio.file.attribute.PosixFilePermission.GROUP_READ;
import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.EnumSet;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    Path path = Paths.get("test");
    PosixFileAttributeView posixView = Files.getFileAttributeView(path,
        PosixFileAttributeView.class);
    if (posixView == null) {
      System.out.format("POSIX attribute view is not supported%n.");
      return;/*from   w  w  w. j  a v a 2 s .  com*/
    }

    readPermissions(posixView);
    updatePermissions(posixView);
  }

  public static void readPermissions(PosixFileAttributeView posixView) {
    try {
      PosixFileAttributes attribs;
      attribs = posixView.readAttributes();
      Set<PosixFilePermission> permissions = attribs.permissions();

      // Convert the set of posix file permissions into rwxrwxrwx form
      String rwxFormPermissions = PosixFilePermissions.toString(permissions);
      System.out.println(rwxFormPermissions);
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  public static void updatePermissions(PosixFileAttributeView posixView) {
    try {
      Set<PosixFilePermission> permissions = EnumSet.of(OWNER_READ,
          OWNER_WRITE, GROUP_READ);
      posixView.setPermissions(permissions);
      System.out.println("Permissions set successfully.");
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

Result

Related Topic