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並設置文件的路徑
相關用法
- Java File isDirectory()用法及代碼示例
- Java File listFiles()用法及代碼示例
- Java File createTempFile()用法及代碼示例
- Java File canRead()用法及代碼示例
- Java File canWrite()用法及代碼示例
- Java File delete()用法及代碼示例
- Java File getName()用法及代碼示例
- Java File getPath()用法及代碼示例
- Java File setLastModified()用法及代碼示例
- Java File canExecute()用法及代碼示例
- Java File isHidden()用法及代碼示例
- Java File createNewFile()用法及代碼示例
- Java File setExecutable()用法及代碼示例
- Java File getFreeSpace()用法及代碼示例
- Java File getTotalSpace()用法及代碼示例
注:本文由純淨天空篩選整理自andrew1234大神的英文原創作品 File setReadOnly() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。