How to make file read only in java

 Posted On  | Yashwant Chavan 

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

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


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0317 seconds.