【问题标题】:How to set file owner/group when creating a file in Java在 Java 中创建文件时如何设置文件所有者/组
【发布时间】:2015-10-29 09:06:12
【问题描述】:

我想设置从 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] 上得到回答),但是何时 em> 文件已创建。

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

【问题讨论】:

    标签: java unix posix


    【解决方案1】:

    似乎无法在文件创建时设置所有权。当你查看open() system call的文档时,它描述了如何设置文件权限,但唯一提到的所有者是:

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

    另见this answer

    我最终找到的解决方案是这样的:

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

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

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

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

    【讨论】:

      【解决方案2】:

      Oracle-Documentation 描述了如何设置和获取符合 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);
      

      【讨论】:

      • 感谢您的回答,除非我找到其他解决方案,否则我会使用它。但这不会在文件 creation 中设置所有者,对吧?我相信Files.setOwner() 期望该文件已经存在。
      猜你喜欢
      • 2020-01-30
      • 2012-06-04
      • 2013-05-26
      • 1970-01-01
      • 2012-03-01
      • 2013-09-23
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多