简体   繁体   中英

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

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?

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

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

Path p = 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...

Take a look at the package java.nio.file.attributes and class PosixFilePermissions . This is where you can manipulate group permissions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM