Open In App

File setReadOnly() method in Java with examples

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The setReadOnly() method is a part of File class. The setReadOnly() function marks the specified file or directory such that only read operations are allowed on the file or directory.

Function Signature:

public boolean setReadOnly()

Syntax:

file.setReadOnly()

Parameters: The function do not requires any parameters.

Return Value: The function returns boolean data type. The function returns true if the File object could be set as Read Only else false.

Exception: This method throws SecurityException if the method does not allow write access to the file

Below programs will illustrate the use of setReadOnly() function:

Example 1: Set existing file “F:\program.txt” to read only




// 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");
        }
    }
}


Output:

File set as Read Only

Example 2: Set non existing file “F:\program1.txt” to read only




// 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");
        }
    }
}


Output:

File cannot be set as Read Only

The programs might not run in an online IDE. please use an offline IDE and set the path of the file



Last Updated : 28 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads