Java - ACL File Permissions

Introduction

ACL type file attributes are supported on Microsoft Windows.

An ACL consists of an ordered list of access control entries.

AclEntry class represents an entry in an ACL.

You can get and set a List of AclEntry for a file using the getAcl() and setAcl() methods of the AclFileAttributeView.

The following code gets the List of ACL entries for a file called C:\myData\Main.java:

Path path = Paths.get("C:\\myData\\Main.java");
AclFileAttributeView view =
        Files.getFileAttributeView(path, AclFileAttributeView.class);
List<AclEntry> aclEntries = view.getAcl();

The following code demonstrates how to read ACL entries for file C:\myData\Main.java.

If the file does not exist, a NoSuchFileException is thrown.

Demo

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.AclFileAttributeView;
import java.util.List;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    // Change the path to an existing file on Windows
    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 ww  . j a  va2  s .com
    }

    try {
      List<AclEntry> aclEntries = aclView.getAcl();
      for (AclEntry entry : aclEntries) {
        System.out.format("Principal: %s%n", entry.principal());
        System.out.format("Type: %s%n", entry.type());
        System.out.format("Permissions are:%n");

        Set<AclEntryPermission> permissions = entry.permissions();
        for (AclEntryPermission p : permissions) {
          System.out.format("%s %n", p);
        }

      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result

Related Topics