如何使用 Java 在 Windows 文件上设置 "modify" ACL



如何使用Java 7的File API设置Windows ACL,使其模拟添加用户/组和以下选项:

例如,在操作系统属性对话框中,您可以选择以下内容进行基本写入访问:

  • 修改
  • ☑读取并执行(自动选择(
  • ☑列出文件夹内容(自动选择(
  • ☑读取(自动选择(
  • ☑写入(自动选择(

但是,当我使用Java7的文件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属性文件权限,方法是创建一个我想要模拟的文件夹,通过"属性"对话框设置值,然后将其回显。。。

// 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();

现在,"Modify"(修改(被完全按照需要选中。

最新更新