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.
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
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().
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.