Read-Only is the file attribute that the operating system assigns to the file. When the file is flagged as read-only, it means that it can only be opened or read, one cannot change the name of the file, can not rewrite or append the content of the file, and also cannot delete the file.
Method 1:
Using setLastModified Method
To make the file read-only, setReadOnly() method of File Class is used. This method returns the boolean value, which is used to check whether the task(to make the file read-only) got successful or not. If the value returned by the method is true, it means that the task was successful and vice versa.
Parameters: The function doesn’t require 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 to write access to the file
Java
import java.io.File;
public class GFG {
public static void main(String[] args)
{
boolean flag;
try {
File file = new File( "/home/mayur/GFG.java" );
file.createNewFile();
flag = file.setReadOnly();
System.out.println( "Is File is read-only ? : "
+ flag);
flag = file.canWrite();
System.out.println( "Is File is writable ? : "
+ flag);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output:

Method 2: Using setWritable() method
Here by passing “false” as an argument to the setWritable() method, we can make a file read only.
The following code will help you understand how to make a file read only using setWritable().
Java
import java.io.File;
public class ChangetoReadOnly {
public static void main(String[] args)
{
try {
File file = new File(
file.setWritable( false );
if (!file.canWrite()) {
System.out.println(
"This File is read only." );
}
else {
System.out.println(
"This File is writable." );
}
}
catch (Exception e) {
System.out.println(
"Sorry unable to change to readonly mode." );
}
}
}
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Jul, 2021
Like Article
Save Article