001package com.ganteater.ae.util; 002 003import java.io.File; 004import java.nio.file.FileSystems; 005import java.util.regex.Pattern; 006 007import org.apache.commons.io.filefilter.IOFileFilter; 008 009public class RegexPathFilter implements IOFileFilter { 010 private Pattern fileNamePattern; 011 private Pattern pathPattern; 012 013 /** 014 * Constructor to compile the regex pattern. 015 * 016 * @param fileFilterRegex The regular expression to match against the file name. 017 * @param dirFilterRegex The regular expression to match against the full path. 018 * @param fileFilterRegex 019 */ 020 public RegexPathFilter(String fileFilterRegex, String dirFilterRegex) { 021 this.fileNamePattern = Pattern.compile(fileFilterRegex); 022 if (dirFilterRegex != null) { 023 this.pathPattern = Pattern.compile(dirFilterRegex); 024 } 025 } 026 027 /** 028 * This method is called by FileUtils.listFiles when checking a file's 029 * directory. The `file` parameter is the directory being scanned. 030 * 031 * @param file The directory to check. 032 * @return true if the directory's full path matches the regex, false otherwise. 033 */ 034 @Override 035 public boolean accept(File file) { 036 boolean result = true; 037 String absolutePath = file.getParent(); 038 if (pathPattern != null) { 039 result = pathPattern.matcher(absolutePath + FileSystems.getDefault().getSeparator()).matches(); 040 } 041 042 if (result) { 043 result = fileNamePattern.matcher(file.getName()).matches(); 044 } 045 return result; 046 } 047 048 // The other accept method is required by the IOFileFilter interface 049 @Override 050 public boolean accept(File dir, String name) { 051 return accept(new File(dir, name)); 052 } 053}