Introduction
When working with files it is very important to know what permissions do we have with the particular files. Thus, to make our lives slightly easier, java has numerous methods to call and check the permissions on the file we are working on. Permissions can be checked on three levels: execution-only, read-only, write. Execution-only means that the application is allowed to execute the file. Read-only denotes that the particular file can only be read by the application. Write means that the application can write in the file and change its contents.
Along with determining the various file permissions we can also change them to suit our needs for our application. In this blog, we will learn about the various methods that can be used to manage permissions using Java.
Also Read, Multithreading in java, and Duck Number in Java.
Checking File Permissions
A major part of manipulating any file is first knowing the permissible changes that can be made to the file we are working on. This is made significantly easier by the methods introduced in Java.
canExecutable
canExecutable can be used to check whether the file we are searching for actually exists by checking the abstract file pathname. Along with this, it also checks whether the application is allowed to execute the file or not.
Example
import java.io.*;
public class test{
public static void main(String[] args){
File file = new File("D:\\test.txt");
System.out.println(file.canExecute()); //Prints true if pathname exists and application is allowed to execute it.
}
}
canRead
canRead checks whether the application is allowed to read data from the file denoted by the pathname.
Example
import java.io.*;
public class test{
public static void main(String[] args){
File file = new File("D:\\test.txt");
System.out.println(file.canRead()); //Prints true if the application is allowed to read data from it.
}
}
canWrite
canWrite basically checks whether we can write into the file specified by the abstract pathname. Write means that we are allowed to make changes into the content of the files.
Example
import java.io.*;
public class test{
public static void main(String[] args){
File file = new File("D:\\test.txt");
System.out.println(file.canWrite()); //Prints true if pathname exists and application is allowed to write to the file.
}
}