- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.regex.*;
- public class TechFact555FileMatching {
- // Pattern to match with file name
- public static final String FILE_PATTERN = "[a-zA-Z0-9]{6}";
- public static void main(String[] args) {
- List<File> resultFiles = new ArrayList<>();
- TechFact555FileMatching fileMatching = new TechFact555FileMatching();
- // Specify parent folder to fetch files
- fileMatching.listFiles(new File("E:/folder"), resultFiles);
- for (File resultFile : resultFiles) {
- System.out.print(resultFile.getName());
- }
- }
- // Recursively looping into folders to get Files
- void listFiles(File directory, List<File> filesList) {
- File[] filesAndFoldersList = directory.listFiles();
- if (filesAndFoldersList != null) {
- for (File fileOrFolder : filesAndFoldersList) {
- if (fileOrFolder.isDirectory()) {
- listFiles(fileOrFolder, filesList);
- } else if (fileOrFolder.isFile() && Pattern.matches(FILE_PATTERN, fileOrFolder.getName())) {
- filesList.add(fileOrFolder);
- }
- }
- }
- }
- }
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