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

后端 未结 3 498
我在风中等你
我在风中等你 2020-11-30 08:59

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 create

相关标签:
3条回答
  • 2020-11-30 09:21

    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);
    
    0 讨论(0)
  • 2020-11-30 09:32

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

    0 讨论(0)
  • 2020-11-30 09:39

    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...

    0 讨论(0)
提交回复
热议问题