Create Read Only File In Java

How to Create Read only File In Java?

In this Example we are going to learn how to create Read Only File in Java

File class has a method setReadOnly() will use to create file read only

import java.io.File;
public class FileReadOnly {
  public static void main(String[] args) {
        //path of the file you want to make read only
        String strFilePath = "E:/java/text.txt";
         //create file object
        File file = new File(strFilePath);
        /*
         * To make file read only, use setReadOnly method
         */
        boolean success = file.setReadOnly();
       System.out.println("Is file read only now? " + success);
    }
}

 

output

Is file read only now? true  

 

How to check is file read only in Java

public class FileReadOnly {
  public static void main(String[] args) {
        //path of the file you want to make read only
        String strFilePath = "E:/java/text.txt";
      //create file object
        File file = new File(strFilePath);
       boolean isWritable = file.canWrite();
        if(isWritable)
            System.out.println("File is writable");
        else
            System.out.println("File is read only");    
   }
}

output

File is read only  

 

How to write Read Only File in Java

public class FileReadOnly {
    public static void main(String[] args) throws IOException {
        //path of the file you want to make read only
        String strFilePath = "E:/java/text.txt";
        File file = new File(strFilePath);
        /*
         * Check if the file is writable first. If it is not,
         * set it to writable before writing to the file.
         */
        if(!file.canWrite()){
             System.out.println("File is read only. Making it writable");
            file.setWritable(true);
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write("Adding Extra text in Read only file");
        System.out.println("String written to the file");
        bw.close();
    }
}

output

String written to the file