Java I/O How to - Set file attributes, /exists/read/write/readonly/writeonly








Question

We would like to know how to set file attributes, /exists/read/write/readonly/writeonly.

Answer

 /*from   www. ja va 2  s. c  o m*/


import java.io.File;
import java.util.Calendar;
import java.util.Date;

public class Main {
  public static void main(String[] argv) throws Exception {
    File f = new File("name.txt");

    if (!f.exists()) {
      System.out.println("File not found.");
      return;
    }
    if (f.canRead())
      System.out.println("  Readable");
    else
      System.out.println("  Not Readable");

    if (f.canWrite())
      System.out.println("  Writable");
    else
      System.out.println("  Not Writable");
    System.out.println("  Last modified on " + new Date(f.lastModified()));

    long t = Calendar.getInstance().getTimeInMillis();
    if (!f.setLastModified(t))
      System.out.println("Can't set time.");

    if (!f.setReadOnly())
      System.out.println("Can't set to read-only.");

    if (f.canRead())
      System.out.println("  Readable");
    else
      System.out.println("  Not Readable");

    if (f.canWrite())
      System.out.println("  Writable");
    else
      System.out.println("  Not Writable");
    System.out.println("  Last modified on " + new Date(f.lastModified()));

    if (!f.setWritable(true, false))
      System.out.println("Can't return to read/write.");

    if (f.canRead())
      System.out.println("  Readable");
    else
      System.out.println("  Not Readable");

    if (f.canWrite())
      System.out.println("  Writable");
    else
      System.out.println("  Not Writable");
  }
}

The code above generates the following result.