📜  Java中的文件 setReadOnly() 方法及示例

📅  最后修改于: 2022-05-13 01:58:09.636000             🧑  作者: Mango

Java中的文件 setReadOnly() 方法及示例

setReadOnly()方法是 File 类的一部分。 setReadOnly()函数标记指定的文件或目录,以便只允许对该文件或目录进行读取操作。

函数签名:

public boolean setReadOnly()

句法:

file.setReadOnly()

参数:该函数不需要任何参数。

返回值:函数返回布尔数据类型。如果文件对象可以设置为只读,则该函数返回 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并设置文件路径