Java 檔案、資料夾許可權修改
阿新 • • 發佈:2019-01-25
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