How to set file permissions using java NIO2 on Windows?

2k Views Asked by At

Are there any ways of setting file permissions using java8 NIO2 on Windows different from this?

file.setReadable(false, false);
file.setExecutable(false, false);
file.setWritable(false, false);
1

There are 1 best solutions below

0
Boris On

The File methods that set various attributes: setExecutable, setReadable, setReadOnly, setWritable are replaced by the Files method setAttribute(Path, String, Object, LinkOption...).

Usage Example:

public void setFileAttributes() throws IOException {
  Path path = ...

  UserPrincipal user = path.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("user");
  AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
  AclEntry entry = AclEntry.newBuilder()
          .setType(ALLOW)
          .setPrincipal(user)
          .setPermissions(Set.of(READ_DATA, EXECUTE, WRITE_DATA))
          .build();
  List<AclEntry> acl = view.getAcl();
  acl.add(0, entry);

  Files.setAttribute(path, "acl:acl", acl);
}

See AclFileAttributeView for more details.