Java File canRead() method with examples

January 04, 2020 No comments Java IO File Examples

1. Introduction

The canRead() checks if the application can read the specified file. Note that this method similar to canExecute() may return true even though the file does not have read permissions when we start JVM with special parameters.

2. Method signature

public boolean canRead()

Parameters:

  • method does not take any parameter

Returns

  • true - if file exists in the filesystem and application can read it

Throws

  • SecurityException - when application do not have access to the file

3. Examples

3.1. The program that checks if the file under /tmp/frontbackend.txt is readable

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/frontbackend.txt");
            boolean canRead = f.canRead();

            if (canRead) {
                System.out.println("Application can read the file");
            } else {
                System.out.println("Application cannot read the file");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If the file does not exists or application does not have permission to read it we will get the following output:

Application cannot read the file

If the file /tmp/frontbackend.txt exists and can be read by the application we will get:

Application can read the file

4. Conclusion

In this article we presented File.canRead() a method that checks if an application can read the file specified by pathname. Keep in mind that JVM can be started with special parameters that change the behavior of the applications, and files without reading permissions could be classified as readable.

{{ message }}

{{ 'Comments are closed.' | trans }}