Set file attributes in Java


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("
Readable");          else             System.out.println("
Not 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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

406 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements