I have a Linux server and I’m running an image resize job in Java for multiple websites on my server. The website files are owned by different OS users/groups. Newly created thumbnails/previews are owned by the user running the resize job. Now I was googleing around how to change the file owner of newly created previews/thumbnails in my resize program and came across this:
java.nio.file.Files.setOwner(Path path, UserPrincipal owner);
This would really solve my problem if it was Windows, but since a Linux file has a user and a group as owner I’m a bit in trouble. Unfortunately given method seems to only change the user ownership of the file. The group ownership remains with the group of the user running my Java resize job.
The websites are owned by different groups, so adding my resize job user to one group is no option. I also want to avoid system calls with ProcessBuilder
and execute a chown
on my files.
I do need to point out that the created files (preview/thumbnail) can be accessed via the website and it is not mission critical to change the group ownership, but I wanted it to be as clean as possible.
Any suggestions how I can change the group ownership of a file in Linux only using Java?
Advertisement
Answer
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);