File Permission


File Permission

To access a file or a directory, we have Java.io.FilePermission class. It contains the pathname and a set of actions valid for that pathname. The permissions which can be given are "read", "write", "execute", and "delete". This class inherits methods from the following classes: Java.io.Permission and Java.io.Object .

Java has several methods through which we can access, change and check the file permission, such as whether a file is on read-only mode or anyone can have permission to edit the file. When the user wants to restrict the outsider from using the file, the user can change the file’ according to their needs.

Syntax for java.io.FilePermission class:

public final class FilePermission extends Permission implements Serializable  

File Permissions

  • Executable

      public boolean canExecute() A file is said to be executable if the given pathname is correct. It returns the boolean value for the execution of the file.

  • Readable

      public boolean canRead() A file can be readable if the file is present in the given path and can have permission to read.

  • Writeable

      public boolean canWrite() If the file is present in the given abstract path, it will check whether the file has permission to write on it; if the user allows or permits the applicant to write, it will return true.

Methods through which we can get the permission of the file:

  • setExecutable

      public boolean setExecutable(boolean executable) If the user allows making changes with the access permission, then this method will work; otherwise, this method will fail.

  • setReadable

      public boolean setReadable(boolean readable) If the user allows making changes with the access permission, then this method will work; otherwise, this method will also fail.

  • setWritable

      public boolean setWritable(boolean writable) If the user allows making changes with the access permission, then this method will work; otherwise, this method will fail again.

The syntax for java.io.FilePermission class:

public final class FilePermission extends Permission implements Serializable

Example:

Com.knowledge2life import java.io.*; public class Main { public static void main(String[] args) { File file = new File("C:\\Users\\Zaman\\Desktop\\knowledge2life.txt"); // check if the file exists boolean exists = file.exists(); if(exists == true) { // printing the permissions associated with the file System.out.println("Executable: " + file.canExecute()); System.out.println("Readable: " + file.canRead()); System.out.println("Writable: "+ file.canWrite()); } else { System.out.println("File not found."); } } }

OUTPUT:

File not found.