Java.io.File.setReadOnly() Method

Advertisements


Description

The java.io.File.setReadOnly() method switches the file to read only mode and denies any write operations on the file.

Declaration

Following is the declaration for java.io.File.setReadOnly() method:

public boolean setReadOnly()

Parameters

  • NA

Return Value

This method returns true if the operation succeeded, else false.

Exception

  • SecurityException -- If a security manager exists and its method denies write access to either the old or new pathnames.

Example

The following example shows the usage of java.io.File.setReadOnly() method.

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
      boolean bool = false;
      
      try{      
         // create new File object
         f = new File("C:/test.txt");
         
         // returns true if file exists
         bool = f.exists();
         
         // if file exists
         if(bool)
         {
            // set file as read only
            bool = f.setReadOnly();
            
            // print
            System.out.println("setReadonly() succeeded?: "+bool);
            
            // checks whether the file is writable
            bool  = f.canWrite();
            
            // prints
            System.out.print("Is file writable?: "+bool);
         }      
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}

Let us compile and run the above program, this will produce the following result:

setReadonly() succeeded?: true
Is file writable?: false



Advertisements
Advertisements