Set file attributes in Java

Java 8Object Oriented ProgrammingProgramming

One of the file attribute that can be set is to make the file read-only. This can be done by using the method java.io.File.setReadOnly(). This method requires no parameters and it returns true if the file is set to read-only and false otherwise.

The java.io.File.canRead() and java.io.File.canWrite() methods are used to check whether the file can be read or written to respectively.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         if (file.canRead())
            System.out.println("Readable");
         else
            System.out.println("Not Readable");
         if (file.canWrite())
            System.out.println("Writable");
         else
            System.out.println("Not Writable");
            file.setReadOnly();
         if (file.canRead())
            System.out.println("\nReadable");
         else
            System.out.println("\nNot Readable");
         if (file.canWrite())
            System.out.println("Writable");
         else
            System.out.println("Not Writable");
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The output of the above program is as follows −

Output

Readable
Writable
Readable
Not Writable
raja
Published on 25-Feb-2019 08:12:55
Advertisements