Change File Owner Group Under Linux with Java.Nio.Files

Change file owner group under Linux with java.nio.Files

Thanks Jim Garrison for pointing me in the correct direction. Here the code, which finally solved the problem for me.

Retrieve the group owner of a file

File originalFile = new File("original.jpg"); // just as an example
GroupPrincipal group = Files.readAttributes(originalFile.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS).group();

Set the group owner of a file

File targetFile = new File("target.jpg");
Files.getFileAttributeView(targetFile.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(group);

How to set file owner/group when creating a file in Java

Setting ownership on file creation does not seem to be possible. When you look at the documentation of open() system call, it describes how to set file permissions, but the only mention of owner is:

If the file does not exist it will be created. The owner (user ID) of the file is set to the effective user ID of the process. The group ownership (group ID) is set either to the effective group ID of the process or to the group ID of the parent directory

See also this answer.

The solution I went for in the end was this:

  1. Create the file with default owner but restrictive permissions 000:

    Path file = ...;
    Set<PosixFilePermission> perms = Collections.<PosixFilePermissions>emptySet();
    FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
    Files.createFile(file, attr);
  2. Change the owner/group to the target user

  3. The target user then sets permissions to what it needs.

This should ensure that no other user can modify the file at any point in time.

Changing group of a unix file using java

You should be able to use PosixFileAttributeView.setGroup() with POSIX systems.

How do I programmatically change file permissions?

Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set on an existing file with setPosixFilePermissions(), or atomically at file creation with methods like createFile() or newByteChannel().

You can create a set of permissions using EnumSet.of(), but the helper method PosixFilePermissions.fromString() will uses a conventional format that will be more readable to many developers. For APIs that accept a FileAttribute, you can wrap the set of permissions with with PosixFilePermissions.asFileAttribute().

Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);

In earlier versions of Java, using native code of your own, or exec-ing command-line utilities are common approaches.



Related Topics



Leave a reply



Submit