我想设置一个(unix)所有者和使用Java创建的文件组。我想要类似this:
的内容Path file = ...;
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(file, attr);
-这是一个如何设置权限的示例,但我找不到与所有者/组相同的方法。
请注意,我对更改所有者不感兴趣之后已创建文件(已在SO[1][2]上得到回答),但是何时已创建文件。
此问题的动机是,在设置适当的所有者和权限时,我需要确保正在创建的文件没有被其他用户修改。
似乎无法设置文件创建的所有权。当您查看open()
system call的文档时,它描述了如何设置文件权限,但唯一提及所有者的是:
如果文件不存在,将创建它。文件的所有者(用户ID)设置为进程的有效用户ID。组所有权(组ID)设置为进程的有效组ID或父目录的组ID
另请参见open()
。
我最后寻求的解决方案是这样:
创建具有默认所有者但具有限制权限的文件this answer:
000
将所有者/组更改为目标用户
这应确保没有其他用户可以在任何时间修改文件。
Path file = ...;
Set<PosixFilePermission> perms = Collections.<PosixFilePermissions>emptySet();
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
Files.createFile(file, attr);
描述如何设置和获取posix一致性所有者。
Oracle-Documentation
Function Prototype看起来像这样:
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();