make a file read only java

The setReadOnly() method of File class is used to make a file read only in java. It returns true is the operation is successful else return false.

Example:

package com.w3schools;
 
import java.io.File;
 
public class ReadOnlyFileTest {
  public static void main(String args[]){
      try {
    	 //File
     	 File file = new File("D:/Test files/file 3.txt");
     	 //Convert the file read only
     	 if(file.setReadOnly()){
     	    System.out.println("File converted to readonly successfully");
         }else{
     	    System.out.println("File not converted to readonly successfully");
     	 }
      } catch (Exception e) {
          e.printStackTrace();
      } 
  }
}

Output:

Stored data in temporary file.
File converted to readonly successfully

Download this example.