Java 文件、文件夹权限修改

来源:互联网 发布:java如何写接口 编辑:程序博客网 时间:2024/05/14 14:44

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.txtrm test.txt

这时就会出现安全隐患。

NIO方式

private void changeFolderPermission(File dirFile) throws IOException {    Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();    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

0 0