Create a File and Set it to Read-Only in Java



In this article, we will learn to use Java to make a file read-only and check if it can still be written. A file can be set to read-only by using the method java.io.File.setReadOnly(). This method requires no parameters and returns true if the file is set to read-only and false otherwise. The method java.io.File.canWrite() is used to check whether the file can be written in Java and if not, then the file is confirmed to be read-only.

Problem Statement

The task is to write a Java program that makes the file read-only and then checks whether the file can still be written after that.
Input
The program will create a file called "demo1.txt" and work with that file.
Output
File is read-only?: true
File is writable?: false

Steps to set a file as read-only and check if it's writable

The following are the steps to set a file as read-only and check if it's writable ?
  • Import the File class from java.io package.
  • Create a File object representing the file you're going to work with.
  • Use the createNewFile() method to ensure the file exists.
  • Set the file to read-only by calling the setReadOnly() method.
  • Use canWrite() to check whether the file is still writable, and print the result.

Java program to set a file to read-only and verify its writable status

A program that demonstrates this is given as follows ?

import java.io.File;
public class Demo {
	public static void main(String[] args) {
		boolean flag;
		try {
			File file = new File("demo1.txt");
			file.createNewFile();
			flag = file.setReadOnly();
			System.out.println("File is read-only?: " + flag);
			flag = file.canWrite();
			System.out.print("File is writable?: " + flag);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

Output

File is read-only?: true
File is writable?: false

Code Explanation

The program creates a file called "demo1.txt" using the createNewFile() method. It then sets the file to read-only with setReadOnly(), and the result (true if successful) is printed. After that, the program checks if the file is writable using canWrite(), which returns false since the file has been set to read-only. The output confirms the file's read-only status and whether it's writable or not. Any errors are handled using a try-catch block.

Updated on: 2024-11-15T18:42:46+05:30

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements