List all files from a directory in Java

In this post, we will learn how to list all files from a directory in Java. We will be covering following techniques.

  1. Use Java8 Stream API.
  2. Using NIO Walk File Tree.
  3. File Walker.
  4. Apache Commons IO

At the end of this post, we will get a deep understanding of the performance for each of these methods and will discuss the best option to list all files recursively from a directory (subdirectories) in Java.

 

1. Using Java8 Steam API

public class ListFilesByStream {

    public static void main(String[] args) throws IOException {

        Path source = Paths.get("/Users/umesh/personal/tutorials/source");
        Files.walk(source).filter(Files::isRegularFile).forEach(System.out::println);
    }
}

Above method will return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

One of the main advantages of this method is Stream which provides flexibility to apply all different operations on returned stream (e.g. limit, grouping etc.).

 

If you want to list all files based on File Attributes or want to filter it, use Files.find() method by passing  BiPredicate.

 

2. Using FileVisitor walkFileTree

FileVisitor walkFileTree provides another convent way to recursively visit all the files in a file tree. We can use it to walk through the tree to perform any operation

  1. Read Files.
  2. Delete Files
  3. Move Files 

Please read  Deleting Directory in Java and Copy a File or Directory in Java to understand how to use FileVisitor to list all files from a directory in Java.

 

3. Using Apache Commons

public class ListFilesByApache {

    public static void main(String[] args) throws IOException {

        File source = new File("/Users/umesh/personal/tutorials/source");
        List<File> files = (List<File>) FileUtils.listFiles(source, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        for (File file : files) {
            // work on the files
        }
    }
}

You can also use iterateFiles to iterate in the source directory. While using Apache Commons File Utils, keep in mind following points.

  1. You can use fileFilter and dirFilter to filter files and directories.
  2. Subdirectories will not be included in the search by default, We have used TrueFileFilter.INSTANCE to include all files and subdirectories.
  3. Use FileFilterUtils to filter specific files/ directories from the search.

 

Performance

Benchmarking tests of recursively iterating through the files and directories indicate that Java8 Stream API is the fastest and Apache Commons IO was the slowest.

In case you are ready using Java8 (Which you should), use Java8 Stream API, else use Java7 NIO Walk tree method.

 

All the code of this article is available Over on Github. This is a Maven-based project.

References

  1. FileUtils
  2. Files#walk
  3. Files#find
  4. BiPredicate
  5. FileFilterUtils