java中怎麼設定檔案許可權

來源:互聯網
上載者:User


檢查檔案許可權允許:

1.file.canExecute(); – 返回true,檔案是可執行檔,false 則不是。
2.file.canWrite(); – 返回true,檔案是可寫的,false 則不是。
3.file.canRead(); – 返回true,檔案是可讀的,false 則不是。

設定檔案許可權:

1.file.setExecutable(boolean); – true允許執行操作; false則是禁止它。
2.file.setReadable(boolean); – true允許讀操作; false則是禁止它。
3.file.setWritable(boolean); – true允許寫操作; false則是禁止它。

在* nix的系統中,可能需要配置有關檔案許可權的詳細指定,例如設定777許可權的檔案或目錄,但是,Java的IO類沒有現成的方法,但你可以使用下面的解決方案:

Runtime.getRuntime().exec("chmod 777 file");檔案許可權的例子

 代碼如下 複製代碼

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();
  }
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.