Java File listFiles() method with examples

April 29, 2020 No comments Java IO File Examples listFiles

1. Introduction

The listFiles() method returns an array of File objects that represent files and directories located on the specified path. The method is similar to list() but in this case we have handler to file instead of just a name in String.

2. Method signature

public File[] listFiles()


  • method does not take any parameter


  • File[] - an array File objects. The array will be empty if the directory is empty.


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

3. Examples

3.1. Code that prints names of the files from /tmp/ttt directory


import java.util.Arrays;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File tmp = new File("/tmp/ttt");

            File[] list = tmp.listFiles();

            if (list != null) {
                      .forEach(file -> {
                          System.out.println(file.getPath() + " " + (file.isDirectory() ? "dir" : "file"));

        } catch (Exception e) {

The output:

/tmp/ttt/zzz dir
/tmp/ttt/dest.txt file
/tmp/ttt/test.txt file

4. Conclusion

In this article, we presented listFiles() method that could be used to get an array of File objects representing files or directories on the specified path in the filesystem.

{{ message }}

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