File setReadOnly() method in Java with examples
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
import java.io.*;
public class GFG {
public static void main(String args[])
{
File f = new File( "F:\\program.txt" );
if (f.setReadOnly()) {
System.out.println( "File set as Read Only" );
}
else {
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
import java.io.*;
public class GFG {
public static void main(String args[])
{
File f = new File( "F:\\program1.txt" );
if (f.setReadOnly()) {
System.out.println( "File set as Read Only" );
}
else {
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
Share your thoughts in the comments
Please Login to comment...