当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。