How do I programmatically change file permissions?

前端 未结 12 1043
深忆病人
深忆病人 2020-11-22 04:55

In Java, I\'m dynamically creating a set of files and I\'d like to change the file permissions on these files on a linux/unix file system. I\'d like to be able to execute t

12条回答
  •  情深已故
    2020-11-22 05:53

    for windows 7 with nio 2.0:

    public static void main(String[] args) throws IOException
    {
        Path file = Paths.get("c:/touch.txt");
        AclFileAttributeView aclAttr = Files.getFileAttributeView(file, AclFileAttributeView.class);
        System.out.println(aclAttr.getOwner());
        for(AclEntry aclEntry : aclAttr.getAcl()){
            System.out.println(aclEntry);
        }
        System.out.println();
    
        UserPrincipalLookupService upls = file.getFileSystem().getUserPrincipalLookupService();
        UserPrincipal user = upls.lookupPrincipalByName(System.getProperty("user.name"));
        AclEntry.Builder builder = AclEntry.newBuilder();       
        builder.setPermissions( EnumSet.of(AclEntryPermission.READ_DATA, AclEntryPermission.EXECUTE, 
                AclEntryPermission.READ_ACL, AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.READ_NAMED_ATTRS,
                AclEntryPermission.WRITE_ACL, AclEntryPermission.DELETE
        ));
        builder.setPrincipal(user);
        builder.setType(AclEntryType.ALLOW);
        aclAttr.setAcl(Collections.singletonList(builder.build()));
    }
    

提交回复
热议问题