How to make a file read-only in Java



Problem Description

How to make a file read-only?

Solution

This example demonstrates how to make a file read-only by using file.setReadOnly() and file.canWrite() methods of File class.

import java.io.File;

public class Main {
   public static void main(String[] args) {
      File file = new File("C:/java.txt");
      System.out.println(file.setReadOnly());
      System.out.println(file.canWrite());
   }
}

Result

The above code sample will produce the following result.To test the example,first create a file 'java.txt' in 'C' drive.

true
false

The following is another sample example of file read-only in java

import java.io.File;
import java.io.IOException;

public class FileReadAttribute { 
   public static void main(String[] args) throws IOException { 
      File file = new File("c:/file.txt");
      file.setReadOnly();
   
      if(file.canWrite()) {
         System.out.println("This file is writable");
      } else {
         System.out.println("This file is read only"); 
      } 
      file.setWritable(true);
      if(file.canWrite()) {
         System.out.println("This file is writable");
      } else {
         System.out.println("This file is read only");
      }
   }
}

The above code sample will produce the following result.To test the example,first create a file 'java.txt' in 'C' drive.

This file is read only
This file is read only
java_files.htm
Advertisements