Create a file and change its attribute to read-only in Java


The attribute of a file can be changed to read-only by using the method java.io.File.setReadOnly(). This method requires no parameters and it returns true if the file is set to read-only and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

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();
      }
   }
}

The output of the above program is as follows −

Output

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

Note − The output may vary on Online Compilers.

Now let us understand the above program.

The file can be set to read-only by using the method java.io.File.setReadOnly() and its return value is printed. A code snippet that demonstrates this is given as follows −

File file = new File("demo1.txt");
file.createNewFile();
flag = file.setReadOnly();
System.out.println("File is read-only?: " + flag);

The method java.io.File.canWrite() is used to is confirm that the file is read-only and to do that, its return value is printed. A code snippet that demonstrates this is given as follows −

flag = file.canWrite();
System.out.print("File is writable?: " + flag);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

957 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements