Check If a File or Directory Is Readable in Java



In this article, we will learn to check if a file or directory is readable. We will use the Java File canRead() method of the java.io package to check if a file or directory is readable in Java. This method returns true if the file specified by the abstract path name can be read by an application and false otherwise.

Steps to check if a file or directory is readable

Following are the steps to check if a file or directory is readable ?

  • First we will import the File class from the java.io package
  • Create a public class named Demo.
  • Set up a File object for the file or directory you want to check.
  • Use the canRead() method to see if the file or directory can be read.
  • Use try-catch blocks to manage any errors that might occur.

Example

Below is the example to check if a file or directory is readable ?

import java.io.File;
public class Demo {
    public static void main(String[] args) {
        try {
            File file = new File("demo1.txt");
            file.createNewFile();
            System.out.println("The file can be read? " + file.canRead());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Output

The file can be read? true

Code Explanation

In the above code, we first import the File class from the java.io package. We then define a class Demo with a main method and inside that main method, we create a File object named file which represents a file named "demo1.txt". The createNewFile() method is called on this File object to ensure that the file is created. We then use the canRead() method of the File class to check if the file is readable.

This method returns a boolean value: true if the file can be read and if not then false. The result is then printed to the console. If an exception occurs during file creation or any other I/O operation, it is caught and its stack trace is printed.

Updated on: 2024-08-21T00:09:20+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements