Java I/O How to - Recursively list all files within a directory and sub directories








Question

We would like to know how to recursively list all files within a directory and sub directories.

Answer

/*from  w  w  w  .j  ava  2 s . c o m*/
import java.io.File;
import java.util.ArrayList;


public class Main{
  /**
   * Recursively list all files within a directory and sub directories
   * @param f File to search
   * @param files List of files found
   */
  public static void listFiles(File f, ArrayList<File> files) {
      File[] fs = f.listFiles();
      for (File file : fs) {
          if (file.isFile() && file.getPath().endsWith(".jar")) {
              files.add(file);
          } else if (file.isDirectory()){
              listFiles(file, files);
          }
      }
  }
}