1.

Set permission to a file in Java

Answer»

File permissions are set on the file when the operations PERMISSIBLE for the file need to be restricted by the user.

The permissible permissions for a file are given below:

  1. Readable - This permission TESTS if the application can read the file that is denoted by the abstract path name.
  2. Writable - This permission tests if the application can change the file that is denoted by the abstract path name.
  3. Executable - This permission tests if the application can execute the file that is denoted by the abstract path name.

The methods that can be used to change the permissions of a file are setExecutable, setReadable and setWritable.

A program that demonstrates the permissions of a file is given as follows:

IMPORT java.io.*; public class Demo {    public static void main(String[] args)    {        File f = NEW File("C:\\Users\\Aaron\\Desktop\\text.txt");        boolean exists = f.exists();        if(exists == true)        {            f.setExecutable(true);            f.setReadable(true);            f.setWritable(false);            System.out.println("The File permissions are now changed.");            System.out.println("Executable: " + f.canExecute());            System.out.println("Readable: " + f.canRead());            System.out.println("Writable: "+ f.canWrite());        }        else        {            System.out.println("File not found.");        }    } }

The output of the above program is as follows:

The File permissions are now changed. Executable: true Readable: true Writable: false


Discussion

No Comment Found