Java Program to change a file attribute to writable

Java 8Object Oriented ProgrammingProgramming

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!
raja
Published on 24-Apr-2019 08:59:22
Advertisements