當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java File setReadOnly()用法及代碼示例


setReadOnly()方法是File類的一部分。 setReadOnly()函數標記指定的文件或目錄,以便僅允許對該文件或目錄進行讀取操作。

函數簽名:

public boolean setReadOnly()

用法:


file.setReadOnly()

參數:該函數不需要任何參數。

返回值:該函數返回布爾數據類型。如果File對象可以設置為Read Only,則該函數返回true,否則返回false。

異常:如果該方法不允許對該文件進行寫訪問,則此方法將引發SecurityException

下麵的程序將說明setReadOnly()函數的用法:

範例1:將現有文件“F:\program.txt”設置為隻讀

// Java program to demonstrate 
// the use of File.setReadOnly() method 
  
import java.io.*; 
  
public class GFG { 
  
    public static void main(String args[]) 
    { 
        // create an abstract pathname (File object) 
        File f = new File("F:\\program.txt"); 
  
        // check if the file object 
        // can be set as Read Only or not 
        if (f.setReadOnly()) { 
  
            // display that the file object 
            // is set as Read Only or not 
            System.out.println("File set as Read Only"); 
        } 
        else { 
  
            // display that the file object 
            // cannot be set as Read Only or not 
            System.out.println("File cannot be set"
                               + " as Read Only"); 
        } 
    } 
}

輸出:

File set as Read Only

範例2:將不存在的文件“F:\program1.txt”設置為隻讀

// Java program to demonstrate 
// the use of File.setReadOnly() method 
  
import java.io.*; 
  
public class GFG { 
  
    public static void main(String args[]) 
    { 
        // create an abstract pathname (File object) 
        File f = new File("F:\\program1.txt"); 
  
        // check if the file object 
        // can be set as Read Only or not 
        if (f.setReadOnly()) { 
  
            // display that the file object 
            // is set as Read Only or not 
            System.out.println("File set as Read Only"); 
        } 
        else { 
  
            // display that the file object 
            // cannot be set as Read Only or not 
            System.out.println("File cannot be set"
                               + " as Read Only"); 
        } 
    } 
}

輸出:

File cannot be set as Read Only

這些程序可能無法在在線IDE中運行。請使用離線IDE並設置文件的路徑



相關用法


注:本文由純淨天空篩選整理自andrew1234大神的英文原創作品 File setReadOnly() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。