Java Program to change a file attribute to writable


Let’s say our file is “input.txt”, which is set read-only −

File myFile = new File("input.txt");
myFile.createNewFile();
myFile.setReadOnly();

Now, set the above file to writable −

myFile.setWritable(true);

After that, you can use canWrite() to check whether the file is writable or not.

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) throws Exception {
      File myFile = new File("input.txt");
      myFile.createNewFile();
      myFile.setReadOnly();
      if (myFile.canWrite()) {
         System.out.println("Writable!");
      } else {
         System.out.println("Read only mode!");
      }
      // set file to writable
      myFile.setWritable(true);
      if (myFile.canWrite()) {
         System.out.println("Writable!");
      } else {
         System.out.println("Read only mode!");
      }
   }
}

Output

Read only mode!
Writable!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements