Make a file read only in Java using setReadOnly and setWritable

Updated

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
Comment
Mithlesh Upadhyay Published 6 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials