gpt4 book ai didi

java - 为什么使用 PosixFilePermission 设置目录权限不起作用

转载 作者:行者123 更新时间:2023-11-29 07:29:33 28 4
gpt4 key购买 nike

下面是我的代码:

String DirectoryPath = "/Users/xxx/uploads/image";
Path newDirectoryPath = Paths.get(DirecotryPath);

if (!Files.exists(newDirectoryPath)) {
Set<PosixFilePermission> permissions = PosixFilePermissions.fromString("rwxrwxrwx");
FileAttribute<Set<PosixFilePermission>> fileAttributes = PosixFilePermissions.asFileAttribute(permissions);
Files.createDirectories(newDirectoryPath, fileAttributes);
}

创建目录后,目录的权限不是777。

最佳答案

这是因为实际umask执行用户的设置。

来自 PosixFileAttributeView

When the access permissions are set at file creation time then the actual value of the permissions may differ that the value of the attribute object. The reasons for this are implementation specific. On UNIX systems, for example, a process has a umask that impacts the permission bits of newly created files. Where an implementation supports the setting of the access permissions, and the underlying file system supports access permissions, then it is required that the value of the actual access permissions will be equal or less than the value of the attribute provided to the createFile or createDirectory methods. In other words, the file may be more secure than requested.

例子

Posix.java

// add the omitted import statements
public class Posix {

public static void main(String[] args) throws IOException {
Path newDirectoryPath = Paths.get("/tmp/image");
Files.deleteIfExists(newDirectoryPath);
Set<PosixFilePermission> permissions
= PosixFilePermissions.fromString("rwxrwxrwx");
FileAttribute<Set<PosixFilePermission>> fileAttributes
= PosixFilePermissions.asFileAttribute(permissions);
Files.createDirectories(newDirectoryPath, fileAttributes);
}
}

在shell中执行

$ cd /tmp
$ javac Posix.java

$ umask 001
$ java Posix
$ ls -ld image/

drwxrwxrw-. 2 suboptimal suboptimal 6 Jul 5 12:38 image/

$ umask 002
$ java Posix
$ ls -ld image/

drwxrwxr-x. 2 suboptimal suboptimal 6 Jul 5 12:38 image/

$ umask 004
$ java Posix
$ ls -ld image/

drwxrwx-wx. 2 suboptimal suboptimal 6 Jul 5 12:38 image/

关于java - 为什么使用 PosixFilePermission 设置目录权限不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44923004/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com