17

我有一台 Linux 服务器,我正在为我的服务器上的多个网站运行 Java 中的图像调整大小作业。网站文件由不同的操作系统用户/组拥有。新创建的缩略图/预览归运行调整大小作业的用户所有。现在我正在搜索如何在我的调整大小程序中更改新创建的预览/缩略图的文件所有者并遇到了这个问题:

java.nio.file.Files.setOwner(Path path, UserPrincipal owner);

如果是 Windows,这确实可以解决我的问题,但是由于 Linux 文件有一个用户和一个组作为所有者,所以我有点麻烦。不幸的是,给定的方法似乎只会改变文件的用户所有权。组所有权仍然属于运行我的 Java 调整大小作业的用户组。

这些网站由不同的组拥有,因此无法将我的调整大小作业用户添加到一个组中。我还想避免系统调用并在我的文件上ProcessBuilder执行 a 。chown

我确实需要指出,可以通过网站访问创建的文件(预览/缩略图),更改组所有权并不是关键任务,但我希望它尽可能干净。

关于如何仅使用 Java 更改 Linux 中文件的组所有权的任何建议?

4

3 回答 3

32

感谢 Jim Garrison 为我指明了正确的方向。这是代码,它终于为我解决了这个问题。

检索文件的组所有者

File originalFile = new File("original.jpg"); // just as an example
GroupPrincipal group = Files.readAttributes(originalFile.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS).group();

设置文件的组所有者

File targetFile = new File("target.jpg");
Files.getFileAttributeView(targetFile.toPath(), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setGroup(group);
于 2012-11-11T20:37:23.070 回答
16

我错过了一个完整的解决方案,它来了(其他答案和评论的组合):

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

请注意,只有文件的所有者才能更改其组,并且只能更改为他所属的组...

于 2014-02-17T19:01:38.880 回答
3

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

于 2012-11-05T23:36:30.693 回答