Java File isDirectory() method with examples

November 30, 2019 No comments Java IO File isDirectory Examples

1. Introduction

The isDirectory() method tests whether the file provided is a directory.

2. Method signature

public boolean isDirectory()


  • method does not take any parameter


  • true - if the file indicated by this abstract pathname exists and is a directory


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

3. Examples

3.1. Program that checks if /tmp/frontbackend.txt and /tmp/frontbackend/ are directories


import java.util.Arrays;
import java.util.List;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            List<File> files = Arrays.asList(new File("/tmp/frontbackend.txt"), new File("/tmp/frontbackend"));

            files.forEach(file -> {
                if (file.isDirectory()) {
                    System.out.println(String.format("%s is a directory", file.getAbsolutePath()));
                } else {
                    System.out.println(String.format("%s is not a directory", file.getAbsolutePath()));

        } catch (Exception e) {

The output:

/tmp/frontbackend.txt is not a directory
/tmp/frontbackend is a directory

4. Conclusion

In this article, we presented File.isDirectory the method that checks if given File is a directory in the filesystem. Consider using Files.readAttributes() method if you need to distinguish an I/O exception from the case that the file is not a directory.

{{ message }}

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