The propose of this tutorial is to demonstrate how do I list all files In a directory in Java, unfortunately, such common function isn’t supported in JDK specification standard API.

Recursively list all files in a directory:

import java.io.File;
import java.util.List;
import java.util.ArrayList;

public List<File> listAllSubfiles(File source) {
   //First decline a list, All sub files will add to this list.
   List<File> lists = new ArrayList<File>();
   addSubFilesToList(lists, source);
   return lists;
}

private void addSubFilesToList(List<File> list, File source) {
   //List first top sub files
   File[] files = source.listFiles();
   for (File file : files) {
      list.add(file);
      addSubFilesToList(list, file);
   }
}

The method listAllSubfiles recursively lists children’s sub files and directories until the folder has no children.

List all files which match filename pattern or extension in a directory

JDK has two interfaces FileFilter and FilenameFilter, we can implement the two interfaces to list all sub directories:

public class DirectoryFilter implements FileFilter {
   public boolean accept(File pathname) {
      return pathname.isDirectory();
   }
}

private void addSubFilesToList(List<File> list, File source) {
   //List first top sub files
   File[] files = source.listFiles(new DirectoryFilter());
   for (File file : files) {
      list.add(file);
      addSubFilesToList(list, file);
   }
}
unfortunately