Category Archives: Java 7

Reading Directory/File’s ACL Directly from Java

Prior to Java 7, there’s no way to read a directory/file’s ACL directly from Java. With Java 7, you can write something like this:-

// this can be a directory or a file
String pathName = "C:\\Users\\thundercat\\Desktop";

Path path = Paths.get(pathName);

try {
    FileOwnerAttributeView fileAttributeView = Files.getFileAttributeView(path, FileOwnerAttributeView.class);

    System.out.println("Owner:\n\t" + fileAttributeView.getOwner());

    AclFileAttributeView aclFileAttributeView = Files.getFileAttributeView(path, AclFileAttributeView.class);

    if (aclFileAttributeView != null) {
        System.out.println("ACL: ");
        for (AclEntry aclEntry : aclFileAttributeView.getAcl()) {
            System.out.println("\t" + aclEntry.principal());
            System.out.println("\t\t" + aclEntry.permissions());
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

When you execute the code above, you will get something like this:-

Owner:
	BUILTIN\Administrators (Alias)
ACL: 
	NT AUTHORITY\SYSTEM (Well-known group)
		[APPEND_DATA, WRITE_ATTRIBUTES, DELETE, SYNCHRONIZE, READ_DATA, WRITE_ACL, WRITE_DATA, READ_ATTRIBUTES, WRITE_NAMED_ATTRS, READ_ACL, DELETE_CHILD, WRITE_OWNER, EXECUTE, READ_NAMED_ATTRS]
	BUILTIN\Administrators (Alias)
		[APPEND_DATA, WRITE_ATTRIBUTES, DELETE, SYNCHRONIZE, READ_DATA, WRITE_ACL, WRITE_DATA, READ_ATTRIBUTES, WRITE_NAMED_ATTRS, READ_ACL, DELETE_CHILD, WRITE_OWNER, EXECUTE, READ_NAMED_ATTRS]
	MYDOMAIN\thundercat (User)
		[APPEND_DATA, WRITE_ATTRIBUTES, DELETE, SYNCHRONIZE, READ_DATA, WRITE_ACL, WRITE_DATA, READ_ATTRIBUTES, WRITE_NAMED_ATTRS, READ_ACL, DELETE_CHILD, WRITE_OWNER, EXECUTE, READ_NAMED_ATTRS]