The Wayback Machine - https://web.archive.org/web/20240805062918/https://www.geeksforgeeks.org/java-program-to-make-a-file-read-only/
Open In App

Java Program to Make a File Read-Only

Last Updated : 21 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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




// Java program to make the file as read only
 
import java.io.File;
 
public class GFG {
   
    public static void main(String[] args)
    {
        // flag variable which contains the boolean
        // value returned by setReadOnly() function
        boolean flag;
       
        try {
           
            File file = new File("/home/mayur/GFG.java");
           
            // creates a new file
            file.createNewFile();
           
            // flag the file to be read-only
            flag = file.setReadOnly();
           
            System.out.println("Is File is read-only ? : "
                               + flag);
           
            // checking whether Is file  writable
            flag = file.canWrite();
            System.out.println("Is File is writable ? : "
                               + flag);
        }
       
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Output: 

Java Program to Make a File Read-Only

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(
                "C://Users//sai mohan pulamolu//Desktop//test.txt");
           
            // making the file to read only mode
            file.setWritable(false);
           
            // check if the  file is writable or not
            // if not writable then it is readonly file.
            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:



Previous Article
Next Article

Similar Reads

Java Program to Read Content From One File and Write it into Another File
File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. Now in order to read conte
5 min read
How to make an ArrayList read only in Java
Given an ArrayList, the task is to make this ArrayList read-only in Java. Examples: Input: ArrayList: [1, 2, 3, 4, 5] Output: Read-only ArrayList: [1, 2, 3, 4, 5] Input: ArrayList: [geeks, for, geeks] Output: Read-only ArrayList: [geeks, for, geeks] An ArrayList can be made read-only easily with the help of Collections.unmodifiableList() method. Th
2 min read
How to Make a Collection Read-Only in Java?
The Collections class is used as a data structure to manage the data. We can add, remove, fetch, and update the data in the List, Set, or Map Object. Collections class has default methods for these operations. We can use those methods easily. By default, when we create an object of the Collections class, it will be Both Readable and Writable. Read-
4 min read
Java program to read all mobile numbers present in given file
Given the input text file, read all mobile numbers present and write to some output file. Suppose we have a file names as input.txt and in that input file we have some Mobile Number which are mixed with some other data. Our task is to read the input file line by line and if we find any Number in that line we have to write that Mobile Number to an a
2 min read
Java Program to Read and Print All Files From a Zip File
A zip file is a file where one or more files are compressed together, generally, zip files are ideal for storing large files. Here the zip file will first read and at the same time printing the contents of a zip file using a java program using the java.util.zip.ZipEntry class for marking the zip file and after reading it, the contents inside it wou
4 min read
Java Program to Read Text From File From a Specified Index
In a file system, without reading the previous text we cannot directly access the specific index. Thus, Reading text from a file from the specific index is achieved by skipping all the previous characters of a specified index. To read text from an index n, we need to skip (n-1) bytes. Here, we will use FileInputStream class to read text from the fi
1 min read
Java Program to Read a File to String
There are multiple ways of writing and reading a text file. This is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Given a text file, the task is to read the contents of a file present in a local directory and storing
8 min read
Java Program to Read a Large Text File Line by Line
As we are well verse with this topic let us put more stress in order to figure out minute differences between them. Here we are supposed to read from a file on the local directory where a text file is present say it be 'gfg.txt'. Let the content inside the file be as shown below: Geeks for Geeks. A computer science portal. Welcome to this portal. H
3 min read
Java program to read all Emails present in a Given file
Given a file as input.txt containing some email ids which are mixed with other data. The task is to read this input file line by line and if any email id is found in that line, write that email id to another file, which is output.txt. Example: Input: input.txt Output: output.txt Approach: To detect the email id in that file, a simple solution is Re
3 min read
Read File Into an Array in Java
In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method. To store the content of the file better use the collection storage type instead of a static array as we don't know the exact lines or word count of files. Then convert the collection
8 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg