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

标签 java unix posix

我想设置从 Java 创建的文件的 (unix) 所有者和组。我想要类似 this 的东西:

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

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

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

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

最佳答案

Oracle-Documentation描述如何设置和获取 posix 符合所有者。

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

函数原型(prototype)如下所示:

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

关于java - 在Java中创建文件时如何设置文件所有者/组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31851993/

相关文章:

java - 当我尝试更新一行时,Android ListView 抛出 CurrentModificationException

java - 通过文件 URL 将文件发送到客户端,无需在服务器上下载

Java - 如果单词以用户输入的定界符结尾,则执行 x

unix - Grep 模式重复

linux - Unix:共享内存。 shm_open() 返回 -1

java - 如何使用 Jackson 反序列化对象数组

linux - 比较一组词的出现

linux - 使用父目录和祖父目录重命名文件

c++ - 如何中止 'close' TCP 连接?

c - UNIX/Linux 信号处理 : SIGEV_THREAD