How to make a file read only in java

In this post, we will see how to make a read only file in java. It is very simple. You need to just call java.io.File 's  setReadOnly() method.

1) How to make a file read only

Java program:

package org.arpit.java2blog;

import java.io.File;

public class FileHiddenMain {

 public static void main(String[] args) {
  System.out.println("-----------------");
  // Read the file
  File configFile=new File("/Users/Arpit/Desktop/config.properties");
  configFile.setReadOnly();
  
  if(configFile.canWrite())
  {
   System.out.println("Config file can be writtern");
  }
  else
  {
   System.out.println("config file is read only");
  }

  System.out.println("-----------------");

            }
     }
When you run above program, you will get following output:
-----------------
config file is read only
-----------------

2) How to make it writable  again

If you have made file read only, you can make file writable again by using method setWritable(true).
This method is introduced in java 1.6.

Java program:

package org.arpit.java2blog;

import java.io.File;

public class FileHiddenMain {

 public static void main(String[] args) {
  System.out.println("-----------------");
  // Read the file
  File configFile=new File("/Users/Arpit/Desktop/config.properties");
  configFile.setReadOnly();
  
  if(configFile.canWrite())
  {
   System.out.println("Config file can be written");
  }
  else
  {
   System.out.println("config file is read only");
  }

  System.out.println("-----------------");

  System.out.println("Making config file writable again");
  // this method is available from jdk 1.6
  configFile.setWritable(true);
  
  if(configFile.canWrite())
  {
   System.out.println("Config file can be written");
  }
  else
  {
   System.out.println("config file is read only");
  }

  System.out.println("-----------------");
 }

}





When you run above program, you will get following output:
-----------------
config file is read only
-----------------
Making config file writable again
Config file can be written
-----------------





Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012