如何使用Java 7的File API设置Windows ACL,使其模仿添加用户/组和以下选项:
例如,在“ OS属性”对话框中,可以选择以下基本写访问权限:
但是,当我通过Java 7的File API使用类似的选项时,它会选择:
不仅不仅难以管理(遍历对话框更容易遗漏某些东西,而且其行为与单击这些框不同)。一些UAC提示的行为有所不同。更糟糕的是,由于遍历对话框,很难切换权限(例如,从Windows桌面),从而留出更多出错的机会。
如何使用Java设置这些复选框?
UserPrincipal authenticatedUsers = path.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName("Authenticated Users");
AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
// Create ACL to give "Authenticated Users" "modify" access
AclEntry entry = AclEntry.newBuilder()
.setType(AclEntryType.ALLOW)
.setPrincipal(authenticatedUsers)
.setPermissions(DELETE, DELETE_CHILD, LIST_DIRECTORY, READ_DATA, READ_ATTRIBUTES, ADD_FILE, WRITE_DATA, WRITE_ATTRIBUTES)
.build();
List<AclEntry> acl = view.getAcl();
acl.add(0, entry); // insert before any DENY entries
view.setAcl(acl);
通过创建要模仿的文件夹,通过“属性”对话框设置值,然后将其回显,我可以模仿Windows Properties文件的权限...
// Echo ACL
Path path = Paths.get("C:\\myfolder");
UserPrincipal authenticatedUsers = path.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName("Authenticated Users");
AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
for(AclEntry entry : view.getAcl()) {
if(entry.principal().equals(authenticatedUsers)) {
System.out.println("=== flags ===");
for (AclEntryFlag flags : entry.flags()) {
System.out.println(flags.name());
}
System.out.println("=== permissions ===");
for (AclEntryPermission permission : entry.permissions()) {
System.out.println(permission.name());
}
}
}
输出:
=== flags ===
DIRECTORY_INHERIT
FILE_INHERIT
=== permissions ===
WRITE_NAMED_ATTRS
WRITE_ATTRIBUTES
DELETE
WRITE_DATA
READ_ACL
APPEND_DATA
READ_ATTRIBUTES
READ_DATA
EXECUTE
SYNCHRONIZE
READ_NAMED_ATTRS
然后,我能够将这些值重新插入到原始示例中:
UserPrincipal authenticatedUsers = path.getFileSystem().getUserPrincipalLookupService()
.lookupPrincipalByName("Authenticated Users");
AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
// Create ACL to give "Authenticated Users" "modify" access
AclEntry entry = AclEntry.newBuilder()
.setType(AclEntryType.ALLOW)
.setPrincipal(authenticatedUsers)
.setFlags(DIRECTORY_INHERIT,
FILE_INHERIT)
.setPermissions(WRITE_NAMED_ATTRS,
WRITE_ATTRIBUTES,
DELETE,
WRITE_DATA,
READ_ACL,
APPEND_DATA,
READ_ATTRIBUTES,
READ_DATA,
EXECUTE,
SYNCHRONIZE,
READ_NAMED_ATTRS)
.build();
...现在完全根据需要检查“修改”。