import java.io.File;
import java.io.IOException;
/*
*只能给当前用户赋予对该文件的权限,调用createNewFile()方法默认的权限是644.
*/
public class FilePermission
{
public static void main( String[] args )
{
try {
File file = new File("/home/test3.txt");
if (file.createNewFile()){
System.out.println("File is created!");
//Runtime.getRuntime().exec("chmod 777 /home/test3.txt");
file.setExecutable(true);//设置可执行权限
file.setReadable(true);//设置可读权限
file.setWritable(true);//设置可写权限
System.out.println("is execute allow : " + file.canExecute());
System.out.println("is read allow : " + file.canRead());
System.out.println("is write allow : " + file.canWrite());
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();<pre class="java" name="code"></pre>
}
}
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<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