Thursday, April 23, 2020

Recursively looping into directories and subdirectories to get files that matching with pattern


  1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.regex.*;
  5. public class TechFact555FileMatching {
  6.   // Pattern to match with file name
  7.   public static final String FILE_PATTERN = "[a-zA-Z0-9]{6}";
  8.  
  9.   public static void main(String[] args) {
  10.     List<File> resultFiles = new ArrayList<>();
  11.     TechFact555FileMatching fileMatching = new TechFact555FileMatching();
  12.     
  13.     // Specify parent folder to fetch files
  14.     fileMatching.listFiles(new File("E:/folder"), resultFiles);
  15.    
  16.     for (File resultFile : resultFiles) {
  17.       System.out.print(resultFile.getName());
  18.     }
  19.   }
  20.  
  21.   // Recursively looping into folders to get Files
  22.   void listFiles(File directory, List<File> filesList) {
  23.     File[] filesAndFoldersList = directory.listFiles();
  24.     if (filesAndFoldersList != null) {
  25.       for (File fileOrFolder : filesAndFoldersList) {
  26.         if (fileOrFolder.isDirectory()) {
  27.           listFiles(fileOrFolder, filesList);
  28.         } else if (fileOrFolder.isFile() && Pattern.matches(FILE_PATTERN, fileOrFolder.getName())) {
  29.           filesList.add(fileOrFolder);
  30.         }
  31.       }
  32.     }
  33.   }
  34. }

Pass the Directory to fetch files as first parameter and list of files to add the pattern matching pattern as second parameter into listFiles function.

No comments:

Post a Comment