How to make file read only in java

How to make file read only in java

By Yashwant Chavan, Views 1118, Date 22-May-2012

Marks the file or directory named by this abstract pathname so that only read operations are allowed.

tags java java-file-io

After invoking setReadOnly() method the file or directory is guaranteed not to change until it is marked to allow write access. Returns: true if and only if the operation succeeded; false otherwise

Below java program to demonstrate the use of java.io.File setReadOnly() method to make a file read only.There another method setWritable() which is used to make a file writable again.

package com.net.example;

import java.io.File;

public class FileReadOnlyExample {
	/**
  * @param args
  */
 public static void main(String[] args) {
   File file = new File("c:/test/testfile.txt");
   
  // set Read only
   file.setReadOnly();
   
  if (file.canWrite()) {
   System.out.println("Writable");
  } else {
   System.out.println("Read only");
  }
  
  // Make writable again
  file.setWritable(true);
  
  if (file.canWrite()) {
  System.out.println("Writable");
  } else {
  System.out.println("Read only");
  }
 }
}

Output

Read only
Writable
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]