Java File isFile() method with examples

April 28, 2020 No comments Jav a IO File Examples isFile

1. Introduction

The canExecute() tests whether the specified path is a 'normal' file, so it is not a directory.

2. Method signature

public boolean isFile()

Parameters:

  • method does not take any parameter

Returns

  • true - if pathname exists and is a normal file

Throws

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

3. Examples

3.1. The example code that checks if given File objects are files using isFile() method

package com.frontbackend.java.io;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f1 = new File("/tmp/frontbackend.txt"); // does not exist
            File f2 = new File("/tmp");
            File f3 = new File("/tmp/exists.txt");

            System.out.printf("/tmp/frontbackend.txt - %s%n", f1.isFile()); // false because the file does not exist
            System.out.printf("/tmp - %s%n", f2.isFile()); // false because it is a directory
            System.out.printf("/tmp/exists.txt - %s%n", f3.isFile()); // true file exists and it is a normal file

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

The output:

/tmp/frontbackend.txt - false
/tmp - false
/tmp/exists.txt - true

4. Conclusion

In this article, we presented isFile() method that checks whether a File object represents an actual file in the filesystem. This method will return true only if the file exists and it is not a directory.

{{ message }}

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