Java - Updating ACL entries for a file

Introduction

The following code adds a new ACL entry for a user named yourName.

It adds DATA_READ and DATA_WRITE permissions for the user yourName on the C:\myData\Main.java file.

Demo

import static java.nio.file.attribute.AclEntryPermission.READ_DATA;
import static java.nio.file.attribute.AclEntryPermission.WRITE_DATA;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclEntryPermission;
import java.nio.file.attribute.AclEntryType;
import java.nio.file.attribute.AclFileAttributeView;
import java.nio.file.attribute.UserPrincipal;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    Path path = Paths.get("C:\\myData\\Main.java");

    AclFileAttributeView aclView = Files.getFileAttributeView(path,
        AclFileAttributeView.class);
    if (aclView == null) {
      System.out.format("ACL view is not supported.%n");
      return;//from w w w  . ja  v a 2s  . c  o m
    }

    try {
      // Get UserPrincipal for yourName
      UserPrincipal bRiceUser = FileSystems.getDefault()
          .getUserPrincipalLookupService().lookupPrincipalByName("yourName");

      // Prepare permissions set
      Set<AclEntryPermission> permissions = EnumSet.of(READ_DATA, WRITE_DATA);

      // Let us build an ACL entry
      AclEntry.Builder builder = AclEntry.newBuilder();
      builder.setPrincipal(bRiceUser);
      builder.setType(AclEntryType.ALLOW);
      builder.setPermissions(permissions);
      AclEntry newEntry = builder.build();

      // Get the ACL entry for the path
      List<AclEntry> aclEntries = aclView.getAcl();

      aclEntries.add(newEntry);

      // Update the ACL entries
      aclView.setAcl(aclEntries);

      System.out.println("ACL entry added for yourName successfully");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result

Related Topic