Grant a New Access in an ACL - Java File Path IO

Java examples for File Path IO:ACL File

Description

Grant a New Access in an ACL

Demo Code

import java.io.IOException;
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.List;

public class Main {
  public static void main(String[] args) {
    Path path = Paths.get("C:/folder1/folder2/folder4", "test.txt");
    try {/*from  www.jav  a2s  . co m*/
      UserPrincipal user = path.getFileSystem().getUserPrincipalLookupService()
          .lookupPrincipalByName("aprees");
      AclFileAttributeView view = Files.getFileAttributeView(path,
          AclFileAttributeView.class);
      AclEntry entry = AclEntry
          .newBuilder()
          .setType(AclEntryType.ALLOW)
          .setPrincipal(user)
          .setPermissions(AclEntryPermission.READ_DATA,
              AclEntryPermission.APPEND_DATA).build();

      // read ACL
      List<AclEntry> acl = view.getAcl();

      // Insert the new entry
      acl.add(0, entry);

      // re-write ACL
      view.setAcl(acl);
      // or, Files.setAttribute(path, "acl:acl", acl, NOFOLLOW_LINKS);

    } catch (IOException e) {
      System.err.println(e);
    }
  }
}

Result


Related Tutorials