1. 程式人生 > >使用Java修改Linux的檔案或資料夾許可權

使用Java修改Linux的檔案或資料夾許可權

今天做功能碰到了一個情況: 需要在程式中自動在linux的根目錄建立一個路徑,並往裡存圖片。

開始只是簡單的將圖片移動到指定的路徑中,竟然無法訪問。竟分析後發現是因為資料夾和檔案的許可權不夠導致。

以下程式碼是將資料夾和檔案的許可權進行修改的:

/**

* 圖片上傳
* @param file
* @param filename
* @throws IllegalStateException
* @throws IOException
* Seven
* 2018年1月22日 下午4:13:48
*/
@Override
public void storeFile(File file, String filename) throws IllegalStateException, IOException {
File dest = new File(pathResolver.getPath(filename, prefix));
   FileUtils.moveFile(file, dest);
   //設定許可權
   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_EXECUTE); //設定組的讀取許可權
   perms.add(PosixFilePermission.OTHERS_READ); //設定其他的讀取許可權
   perms.add(PosixFilePermission.OTHERS_EXECUTE); //設定其他的讀取許可權

   try {
   //設定檔案和資料夾的許可權
   Path pathParent = Paths.get(dest.getParentFile().getAbsolutePath());
       Path pathDest = Paths.get(dest.getAbsolutePath());
       Files.setPosixFilePermissions(pathParent, perms); //修改資料夾路徑的許可權
       Files.setPosixFilePermissions(pathDest, perms);//修改圖片檔案的許可權
   } catch (Exception e) {
       logger.info(e.getMessage());
   }
}