Java AclFileAttributeView update

Description

Java AclFileAttributeView update

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("Main.java");

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

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

      // Prepare permissions set
      Set<AclEntryPermission> permissions = EnumSet.of(AclEntryPermission.READ_DATA, AclEntryPermission.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();
    }
  }
}



PreviousNext

Related