有没有办法用给定的POSIX权限集创建文件?
一旦文件存在,就可以为文件设置POSIX权限。下面的代码执行此操作。但是,该代码还有一个文件竞争,其中文件打开时可能是松散的权限(CREATION),然后我将其锁定(SECURED)。在某人之间可能已经修改了文件,导致问题。如何在创建时设置权限?
Set<PosixFilePermission> perms =
EnumSet.of(PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE);
Path targetPath = dir.resolve(FILENAME);
String contents = getContent();
try {// CREATION, race starts
try (FileWriter fw = new FileWriter(tempPath.toFile())) {
fw.append(contents);
}
// SECURED, race ends
Files.setPosixFilePermissions(tempPath, perms);
...
答案 0 :(得分:0)
结果是另一个POSIX接口:PosixFileAttributeView你可以将它传递给Files.createFile()
请参阅Setting Intial Permissions部分:
设置初始权限
Implementations supporting this attribute view may also support setting the initial permissions when creating a file or directory.
将以下路径传递给FileWriter是正确的做法:
Path lockedFile = Files.createFile(tempPath,
PosixFilePermissions.asFileAttribute(perms));
try (FileWriter fw = new FileWriter(lockedFile.toFile())) {
...