gpt4 book ai didi

java - java中的chmod根据模式而不是字符串

转载 作者:行者123 更新时间:2023-11-30 07:42:36 25 4
gpt4 key购买 nike

我在 java 中有一个动态 int 表示模式,例如:450、777 等我需要更改现有的文件权限,我尝试探索 Files.setPosixFilePermissions Api 但这需要字符串格式的模式,如 -rw-r--r--

Files.setPosixFilePermissions(
path,
PosixFilePermissions.fromString("-rw-r--r--")
);

但是如果它是数字而不是像 450、777 这样的字符串,它在运行时可以是任何东西,我该如何实现呢?

最佳答案

您可以像这样进行简单的转换:

    public class Chmod {

public Set<PosixFilePermission> fromInt(int perms) {
final char[] ds = Integer.toString(perms).toCharArray();
final char[] ss = {'-','-','-','-','-','-','-','-','-'};
for (int i = ds.length-1; i >= 0; i--) {
int n = ds[i] - '0';
if (i == ds.length-1) {
if ((n & 1) != 0) ss[8] = 'x';
if ((n & 2) != 0) ss[7] = 'w';
if ((n & 4) != 0) ss[6] = 'r';
}
else if (i == ds.length-2) {
if ((n & 1) != 0) ss[5] = 'x';
if ((n & 2) != 0) ss[4] = 'w';
if ((n & 4) != 0) ss[3] = 'r';
}
else if (i == ds.length-3) {
if ((n & 1) != 0) ss[2] = 'x';
if ((n & 2) != 0) ss[1] = 'w';
if ((n & 4) != 0) ss[0] = 'r';
}
}
String sperms = new String(ss);
System.out.printf("%d -> %s\n", perms, sperms);
return PosixFilePermissions.fromString(sperms);
}

public static void main(String[] args) throws Exception {
Chmod test = new Chmod();
test.fromInt(444);
test.fromInt(1);
test.fromInt(777);
test.fromInt(666);
test.fromInt(604);
test.fromInt(0);
}

}

关于java - java中的chmod根据模式而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54421004/

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