如何从 java 中设置 umask?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3175303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:41:38  来源:igfitidea点击:

How can I set the umask from within java?

javafile-permissions

提问by eeee

I'm new to Java. Where is umask exposed in the api?

我是 Java 的新手。umask 在 api 中暴露在哪里?

回答by Yuval Adam

You can't fiddle with the umask directly, since Java is an abstraction and the umask is POSIX-implementation specific. But you have the following API:

您不能直接使用 umask,因为 Java 是一种抽象,而 umask 是特定于 POSIX 实现的。但是您有以下 API:

File f;
f.setExecutable(true);
f.setReadable(false);
f.setWritable(true);

There are some more APIs available, check the docs.

还有更多可用的 API,请查看文档

If you musthave direct access to the umask, either do it via JNI and the chmod()syscall, or spawn a new process with exec("chmod").

如果您必须直接访问 umask,请通过 JNI 和chmod()系统调用进行访问,或者使用exec("chmod").

回答by Ich

import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermission

File file = new File("/some/path") 
Files.setPosixFilePermissions(file.toPath(), [
                PosixFilePermission.OWNER_READ,
                PosixFilePermission.OWNER_WRITE
            ].toSet())

回答by Tom Hawtin - tackline

java.nio.file.attribute.PosixFileAttributesin Java SE 7.

java.nio.file.attribute.PosixFileAttributes在 Java SE 7 中。

回答by Stephen C

Another approach is to use a 3rd-party Java library that exposes POSIX system calls; e.g.

另一种方法是使用公开 POSIX 系统调用的第 3 方 Java 库;例如

The problem with this approach is that it is intrinsically non-portable (won't work on a non-POSIX compliant platform), and requires a platform-specific native library ... and all that that entails.

这种方法的问题在于它本质上是不可移植的(不能在非 POSIX 兼容平台上工作),并且需要一个特定于平台的本机库......以及所有需要的东西。