Java 修改文件权限这个应该是老生常谈的功能,但是最近发现以前写的代码有一点点安全隐患,所以把代码改成 NIO 的方式,下面会介绍 2 种修改文件,文件夹权限的方法。
使用 File 类
这个方式是以前最常见的方式,但是这个方式有点缺点在 LINUX 或者 UNIX 系统下,需要显示的指定权限为 440,770 等就显得不是那么好用了。
File dirFile = new File(dirPath);
dirFile.setReadable(true, false);
dirFile.setExecutable(true, false);
dirFile.setWritable(true, false);
因此我们通常会采用一些 workaround 的方式修改文件夹权限,必须我需要在 LINUX 上设置权限为 770
Runtime runtime = getRuntime();
String command = "chmod 770 " + dirPath;
try {
Process process = runtime.exec(command);
process.waitFor();
int existValue = process.exitValue();
if(existValue != 0){
logger.log(Level.SEVERE, "Change file permission failed.");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Command execute failed.", e);
}
这种方式会有一个问题,当 dirPath 中包含空格或者分号的时候,不仅仅对功能有影响,对安全也是有隐患的。
情况 1: dirPath = /home/a aa.txt
在 LINUX 系统中执行的命令是
chmod 770 /home/a aa.txt 系统会认为修改 /home/a 和 aa.txt 的文件权限为 770,修改文件权限失败
情况 2: 当 dirPath = /home/aaa.txt;rm test.txt
这时在 LINUX 系统中会执行 2 条指令:
chmod 770 /home/omc/aaa.txt
rm test.txt
这时就会出现安全隐患。
NIO 方式
private void changeFolderPermission(File dirFile) throws IOException {
Set perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_EXECUTE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.GROUP_EXECUTE);
try {
Path path = Paths.get(dirFile.getAbsolutePath());
Files.setPosixFilePermissions(path, perms);
} catch (Exception e) {
logger.log(Level.SEVERE, "Change folder " + dirFile.getAbsolutePath() + " permission failed.", e);
}
}
从 API 查询知道,NIO 的这种方式原生支持 LINUX 和 UNIX 低层系统,但测试发现在 Windows 系统下面不区分文件所有者和其它似乎没有效果,这个和实用 File 是一致的。从底层代码发现,还是使用的 File 类 另外可能会抛出 UnsupportedOperationException IOException SecurityException