Home » Java programming language

Java File Class boolean setReadOnly() method with Example

Java File Class boolean setReadOnly() method: Here, we are going to learn about the boolean setReadOnly() method of File class with its syntax and example.
Submitted by Preeti Jain, on July 15, 2019

File Class boolean setReadOnly()

  • This method is available in package java.io.File.setReadOnly().
  • This method is used to check whether file or directory is read-only or not and this method is accessible with the File object.
  • The return type of this method is Boolean i.e. it returns true or false if true that means file or directory can be open for the reading-only purpose we will not be able to modify the file or directory and returns false that means file or directory is not only read mode.
  • This method will throw a security exception if write access is not given to file or directory.

Syntax:

    boolean setReadOnly(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the File.

Return value:

The return type of this method is Boolean, it returns true or false if true that means file or directory is open for reading only purpose else returns false that means file or directory is not only in readable mode.

Java program to demonstrate example of setReadOnly() method

// import the File class because we will use File class methods
import java.io.File;

// import the Exception class because it may raise 
// an exception when working with files
import java.lang.Exception;

public class FileReadmodeOnly {
    public static void main(String[] args) {
        try {
            // Specify the path of file and we use double slashes to 
            // escape '\' character sequence for windows otherwise 
            // it will be considerable as url.
            File file = new File("E:\\Programs\\Thread1.java");

            // By using setReadOnly() method sets the permission for 
            // file or directory is read only it returns Boolean value 
            // if true means file or directory is readable else 
            // return false that means file or directory is not open 
            // for read only purpose.
            if (file.setReadOnly())
                System.out.println("File or Directory can be open in read mode only");
            else
                System.out.println("File or Directory cannot be open in read mode only");
        } catch (Exception e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output

D:\Programs>javac FileReadmodeOnly.java

D:\Programs>java FileReadmodeOnly
File or Directory can be open in read mode only



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.