View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.util;
5   
6   import java.io.File;
7   import java.io.FilenameFilter;
8   import java.util.ArrayList;
9   import java.util.List;
10  
11  /**
12   * A utility class for finding files within a directory.
13   */
14  public class FileFinder {
15  
16      private FilenameFilter filter;
17      private static final String FILE_SEP = System.getProperty("file.separator");
18  
19      public List<File> findFilesFrom(File dir, FilenameFilter filter, boolean recurse) {
20          this.filter = filter;
21          List<File> files = new ArrayList<>();
22          scanDirectory(dir, files, recurse);
23          return files;
24      }
25  
26      /**
27       * Implements a tail recursive file scanner
28       */
29      private void scanDirectory(File dir, List<File> list, boolean recurse) {
30          String[] candidates = dir.list(filter);
31          if (candidates == null) {
32              return;
33          }
34          for (int i = 0; i < candidates.length; i++) {
35              File tmp = new File(dir + FILE_SEP + candidates[i]);
36              if (tmp.isDirectory()) {
37                  if (recurse) {
38                      scanDirectory(tmp, list, true);
39                  }
40              } else {
41                  list.add(new File(dir + FILE_SEP + candidates[i]));
42              }
43          }
44      }
45  }