How to Check if a file is readable and writable

In this post, we are going to check whether a file is readable and writeable or not. Each file in the computer system has properties that specify whether that can be read, write, or execute.

For some security reasons, all the files are not publicly readable or writable. So the Java File class provides methods to check these properties of a file during program execution.

To check read property we use canRead() method and for write, we use canWrite() method of File class.

The canRead() and canWrite() methods both returns a boolean value either true or false. If the file is readable or writeable then we get true from both methods.

Time for an Example:

Let's create an example to check whether a file a readable or not. Here, we are using canRead() method of File class.

import java.io.File;
public class Main {

	public static void main(String[] args){
		try {
			File file = new File("abc.txt");
			boolean canRead = file.canRead();
			if(canRead) {
				System.out.println("File can be read");
			}else {
				System.out.println("File can't be read");
			}
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


File can be read

Example:

Let's create an example to check whether a file is writeable or not. Here, we are using canWrite() method of File class that returns a boolean value.

import java.io.File;
public class Main {

	public static void main(String[] args){
		try {
			File file = new File("abc.txt");
			boolean canWrite = file.canWrite();
			if(canWrite) {
				System.out.println("File is writeable");
			}else {
				System.out.println("File is not writeable");
			}
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


File is writeable

Example:

If a file is writable and we want to make it not writable using the Java code, then we can use setWritable() method of File class that makes a file not writeable see the below example.

import java.io.File;
public class Main {

	public static void main(String[] args){
		try {
			File file = new File("abc.txt");
			boolean canWrite = file.canWrite();
			// Setting file not to writable
			file.setWritable(false);
			if(canWrite) {
				System.out.println("File is writeable");
			}else {
				System.out.println("File is not writeable");
			}
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


File is not writeable