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

Solution 1:

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

Solution 2:

I missed a complete solution, here it comes (combination of other answers and comments):

Path p = Paths.get("your file's Path");
String group = "GROUP_NAME";
UserPrincipalLookupService lookupService = FileSystems.getDefault()
                .getUserPrincipalLookupService();
GroupPrincipal group = lookupService.lookupPrincipalByGroupName(group);
Files.getFileAttributeView(p, PosixFileAttributeView.class,
                LinkOption.NOFOLLOW_LINKS).setGroup(group);

Be aware that only the owner of a file can change its group and only to a group he is a member of...