在 Java 中設定檔案屬性


可設定的檔案屬性之一是將檔案設為只讀。這可以透過使用 java.io.File.setReadOnly() 方法來完成。此方法不需要任何引數,並且如果檔案設定為只讀,則返回 true,否則返回 false。

java.io.File.canRead() 和 java.io.File.canWrite() 方法用於分別檢查是否可以讀取或寫入檔案。

演示這一點的程式如下所示 −

範例

 執行演示

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         if (file.canRead())
            System.out.println("Readable");
         else
            System.out.println("Not Readable");
         if (file.canWrite())
            System.out.println("Writable");
         else
            System.out.println("Not Writable");
            file.setReadOnly();
         if (file.canRead())
            System.out.println("
Readable");          else             System.out.println("
Not Readable");          if (file.canWrite())             System.out.println("Writable");          else             System.out.println("Not Writable");       } catch(Exception e) {          e.printStackTrace();       }    } }

以上程式的輸出如下 −

輸出

Readable
Writable
Readable
Not Writable

更新於:2019 年 7 月 30 日

543 次瀏覽

開始你的職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.