Java.io.File.canWrite() Method

Advertisements


Description

The java.io.File.canWrite() method verifies whether the application can write to the file denoted by this abstract path name.

Declaration

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

public boolean canWrite()

Parameters

  • NA

Return Value

The method returns true if the application to write to the file, else the method returns false.

Exception

  • SecurityException -- If SecurityManager.checkWrite(java.lang.String) method denies write access to the file.

Example

The following example shows the usage of java.io.File.canWrite() 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
         f = new File("test.txt");
         
         // set writable to false
         f.setWritable(false);
         
         // returns boolean
         bool = f.canWrite();
         
         // print
         System.out.println("Can write to test.txt: "+bool);
         
         // set writable to true
         f.setWritable(true);
         
         // returns boolean
         bool = f.canWrite();
         
         // print
         System.out.print("Can write to test.txt: "+bool);
         
      }catch(Exception e){
         // if any I/O error occurs
         e.printStackTrace();
      }
   }
}

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

Can write to test.txt: false
Can write to test.txt: true



Advertisements
Advertisements