繁体   English   中英

在Java中创建文件时如何设置文件所有者/组

[英]How to set file owner/group when creating a file in Java

我想设置从 Java 创建的文件的(unix)所有者和组。 我想类似这样

Path file = ...;
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(file, attr);

-- 这是如何设置权限的示例,但我找不到如何对所有者/组执行相同操作。

请注意,我对在创建文件更改所有者不感兴趣(这已经在 SO [1] [2]上得到了回答),但是创建文件

这个问题的动机是我需要确保我创建的文件在我设置正确的所有者和权限时不被其他用户修改。

似乎不可能在文件创建时设置所有权。 当您查看open()系统调用的文档时,它描述了如何设置文件权限,但唯一提到的所有者是:

如果文件不存在,它将被创建。 文件的所有者(用户 ID)设置为进程的有效用户 ID。 组所有权(组 ID)设置为进程的有效组 ID 或父目录的组 ID

另请参阅此答案

我最终寻求的解决方案是这样的:

  1. 创建具有默认所有者但限制性权限000的文件:

     Path file = ...; Set<PosixFilePermission> perms = Collections.<PosixFilePermissions>emptySet(); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); Files.createFile(file, attr);
  2. 将所有者/组更改为目标用户

  3. 目标用户然后根据需要设置权限。

这应该确保没有其他用户可以在任何时间点修改该文件。

Oracle 文档描述了如何设置和获取符合 posix 的所有者。

Path path = ...
 UserPrincipalLookupService lookupService =
     provider(path).getUserPrincipalLookupService();
 UserPrincipal joe = lookupService.lookupPrincipalByName("joe");
 Files.setOwner(path, joe);

函数原型看起来像这样:

public static Path setOwner(Path path,
        UserPrincipal owner)
                 throws IOException

参数

  • path - 定位文件的文件引用
  • owner - 新的文件所有者

文档中确实没有提到该组:

检索文件的组所有者

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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