The File library of java provides many methods for creating new directories, listing the contents of a directory, path name, deleting or renaming files and modes in which file can be opened such as read, write and append. The following methods have been discussed to make a file read only.
Method 1 : use of setReadOnly() method
This method sets the mode of a file in read-only mode. No manipulation could be done with data once set in read-only. See below example.
import java.io.*;
class Main {
// main method
public static void main(String[] args)
{
// load file
File filename = new File(
"C:\\Users\\user\\example_2.txt");
// set the mode to read only
filename.setReadOnly();
// check if file is in read mode or not
if (filename.canWrite()) {
System.out.println("The file is writable");
}
else {
System.out.println(
"The file is in read-only mode");
}
}
}
Output :
The file is in read-only mode
Method 2 : setWritable() method
This method takes one argument of boolean type. When passed true to this method, it will make file as writable. If you pass false to this method, the file will become read-only.
import java.io.*;
class Main {
// main method
public static void main(String[] args)
{
// load file
File filename = new File(
"C:\\Users\\user\\example_2.txt");
// set the mode to read only
filename.setWritable(false);
// check if file is in read mode or not
if (filename.canWrite()) {
System.out.println("The file is writable");
}
else {
System.out.println(
"The file is in read-only mode");
}
}
}
Output :
The file is in read-only mode