使用java.nio.Files更改Linux下的文件所有者组 [英] Change file owner group under Linux with java.nio.Files

查看:130
本文介绍了使用java.nio.Files更改Linux下的文件所有者组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如果它是Windows,这将真正解决我的问题,但由于Linux文件有用户和小组作为老板我有点麻烦。不幸的是,给定的方法似乎只改变了文件的用户所有权。组所有权保留在运行我的Java调整大小作业的用户组中。

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.

网站由不同的组拥有,因此将我的调整大小作业用户添加到一个组是否定的选项。我还想避免使用 ProcessBuilder 进行系统调用,并在我的文件上执行 chown

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.

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

推荐答案

感谢Jim Garrison指出我正确的方向。这里的代码最终解决了我的问题。

Thanks Jim Garrison for pointing me in the correct direction. Here the code, which finally solved the problem for me.

检索文件的组所有者

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

这篇关于使用java.nio.Files更改Linux下的文件所有者组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆