java 在创建文件对象时将文件权限设置为 777
2022-09-02 14:19:15
Java SE 7 具有 java.nio.file.attribute.PosixFileAttributes,它使您可以对所有者、组和其他人的读取、写入和执行权限进行精细控制。
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Set;
public class Test {
public static void main(String[] args) throws Exception {
Path path = Paths.get("/tmp/test-file.txt");
if (!Files.exists(path)) Files.createFile(path);
Set<PosixFilePermission> perms = Files.readAttributes(path,PosixFileAttributes.class).permissions();
System.out.format("Permissions before: %s%n", PosixFilePermissions.toString(perms));
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_EXECUTE);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_EXECUTE);
perms.add(PosixFilePermission.OTHERS_WRITE);
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_EXECUTE);
Files.setPosixFilePermissions(path, perms);
System.out.format("Permissions after: %s%n", PosixFilePermissions.toString(perms));
}
}
然后可以像这样使用:
$ rm -f /tmp/test-file.txt && javac Test.java && java Test
Permissions before: rw-r--r--
Permissions after: rwxrwxrwx
有 3 种方法可用:
setReadalble(boolean boolean)
setWritable(boolean,boolean)
setExecutable(boolean,boolean)
这会将文件设置为“0777”
String path = "SOME/PATH";
final File file = new File(path);
file.setReadable(true, false);
file.setExecutable(true, false);
file.setWritable(true, false);