我想设置从 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/