Skip to Content

Mark file or directory Read Only

  1. /*
  2.   Mark file or directory Read Only
  3.   This Java example shows how set mark a particular file or directory as a read only
  4.   using setReadyOnly method of Java File class.
  5. */
  6.  
  7. import java.io.*;
  8.  
  9. public class MarkFileReadOnly {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create file object
  14.     File file = new File("C://FileIO//demo.txt");
  15.    
  16.     /*
  17.      * To mark a particular file or directory as a read only, use
  18.      * boolean setReadyOnly() method of Java File class.
  19.      *
  20.      * This method returns true if the operation was successful.
  21.      */
  22.    
  23.      boolean blnMarked  = file.setReadOnly();
  24.    
  25.      System.out.println("Was file marked read only ?: " + blnMarked);
  26.    
  27.      //check whether file is readonly or not using canWrite method
  28.      System.out.println("Is file writable ?: " + file.canWrite());
  29.   }
  30. }
  31.  
  32. /*
  33. Output would be
  34. Was file marked read only ?: true
  35. Is file writable ?: false
  36. */

Advertisement: