In the Java program to check if a file or directory has read and write permission or not, we need to import java.io.file library first which contains all the built-in functions than can check the rights to access of a file.
import java.io.File;
public class permission{
public static void main(String[] args) {
// Create a File object
File my_file_dir = new File("/Desktop/sample.txt");
if (my_file_dir.canWrite())
{
System.out.println(my_file_dir.getAbsolutePath() + " can write.\n");
}
else
{
System.out.println(my_file_dir.getAbsolutePath() + " cannot write.\n");
}
if (my_file_dir.canRead())
{
System.out.println(my_file_dir.getAbsolutePath() + " can read.\n");
}
else
{
System.out.println(my_file_dir.getAbsolutePath() + " cannot read.\n");
}
}
}
Sample Output: /Desktop/sample.txt cannot write. /Desktop/sample.txt cannot read.