Java I/O How to - Change a file attribute to writable








Question

We would like to know how to change a file attribute to writable.

Answer

 // ww  w. j a v a 2s  .c  o  m

 
import java.io.File;

public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("Writable.txt");
    file.createNewFile();
    file.setReadOnly();

    if (file.canWrite()) {
      System.out.println("File is writable!");
    } else {
      System.out.println("File is in read only mode!");
    }
    file.setWritable(true);
    if (file.canWrite()) {
      System.out.println("File is writable!");
    } else {
      System.out.println("File is in read only mode!");
    }
  }
}

The code above generates the following result.