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

Leave a Comment