Java – Check if File is Readable

In this tutorial, we will learn about the Java File.canRead() function, and learn how to use this function to check if this application can read a specified file, with the help of examples.

canRead()

File.canRead() checks whether the file exists and if the application can read this file.

If file exists and application can read the file, canRead() returns true, else it returns false.

The syntax of canRead() function is

</>
Copy
canRead()

Returns

The function returns boolean value.

Examples

1. Positive Scenario – The file is readable

In this example, we will take a file with path "D:\sample.txt". Since the file is present at the location and is readable by the application, canRead() returns true.

Java Program

</>
Copy
import java.io.File;

public class Example {
	public static void main(String args[]) {
		File f = new File("D:\\sample.txt");
		if (f.canRead()) {
			System.out.println("The file is readable."); 
		}
		else {
			System.out.println("The file is not readable."); 
		}
	}
}

Output

The file is readable.

2. Negative Scenario – The file is not present (therefore not readable)

In this example, we will take a file with path "D:\sample_no_file.txt". Make sure that there is no file with the specified path. Since the file is not present, canRead() returns false.

Java Program

</>
Copy
import java.io.File;

public class Example {
	public static void main(String args[]) {
		File f = new File("D:\\sample_no_file.txt");
		if (f.canRead()) {
			System.out.println("The file is readable."); 
		}
		else {
			System.out.println("The file is not readable."); 
		}
	}
}

Output

The file is not readable.

Conclusion

In this Java Tutorial, we have learnt the syntax of Java File.canRead() function, and also learnt how to use this function with the help of examples.