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

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

问题描述

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

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天全站免登陆