Java.io.File.setReadOnly() 方法



描述

java.io.File.setReadOnly() 方法將檔案切換到只讀模式,並拒絕對檔案的任何寫入操作。

宣告

以下是java.io.File.setReadOnly() 方法的宣告:

public boolean setReadOnly()

引數

返回值

如果操作成功,則此方法返回 true,否則返回 false。

異常

SecurityException - 如果存在安全管理器並且其方法拒絕寫入舊路徑名或新路徑名。

示例

以下示例顯示了 java.io.File.setReadOnly() 方法的使用。

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {      
      File f = null;
      boolean bool = false;
      
      try {  
      
         // create new File object
         f = new File("C:/test.txt");
         
         // returns true if file exists
         bool = f.exists();
         
         // if file exists
         if(bool) {
         
            // set file as read only
            bool = f.setReadOnly();
            
            // print
            System.out.println("setReadonly() succeeded?: "+bool);
            
            // checks whether the file is writable
            bool  = f.canWrite();
            
            // prints
            System.out.print("Is file writable?: "+bool);
         }
         
      } catch(Exception e) {
         // if any error occurs
         e.printStackTrace();
      }
   }
}

讓我們編譯並執行上面的程式,這將產生以下結果:

setReadonly() succeeded?: true
Is file writable?: false
java_io_file.htm
廣告
© . All rights reserved.