Reputation: 3245
I have to separate out those files from a folder which matches one of the given pattern. I have an array of strings which contains these patterns.
And I am passing this array as argument into WildCardFilter so that I can separate out thse files which matches the given pattern in the array. My code is given below.
String pat1="DailyExistingBusinessReport_*";
String pat2="*DailyNewExistingBusinessReport_.csv";
String pat3="*_EOD_PNL_Explained.*";
String pat4="ABC*XYZ.csv";
String str[]=new String[]{pat1,pat2,pat3,pat4};
FileFilter fileFilter = new WildcardFileFilter(str);
File dir = new File("\\C:\\Users\\ABC\\Desktop\\Myfiles");
File[] files = dir.listFiles(fileFilter);
for(File f :files){
System.out.println(f);
}
This prints out the name of files which matches the patterns given in array. But now my requirement is that alongwith each file name, I want the exact name of pattern to which this file matched. Any idea what code should I add further to get pattern name alongwith file name.
Upvotes: 1
Views: 2593
Reputation: 6242
I've checked the API and don't see the way to do that with the FileFilter
.
I suggest creating a list of filters and apply them one by one:
List<FileFilter> filters = new ArrayList<FileFilter>();
filters.add(new WildCardFileFilter("DailyExistingBusinessReport_*");
filters.add(new WildCardFileFilter("*DailyNewExistingBusinessReport_.csv");
filters.add(new WildCardFileFilter("*_EOD_PNL_Explained.*");
filters.add(new WildCardFileFilter("ABC*XYZ.csv");
File dir = new File("\\C:\\Users\\ABC\\Desktop\\Myfiles");
Map<FileFilter, List<File>> filemap = new HashMap<FileFilter, List<File>>();
for (File file: dir.listFiles()){
for(FileFilter filter: filters){
if(filter.accept(file)){
if(!filemap.containsKey(filter)){
filemap.put(filter, new ArrayList<File>());
}
filemap.get(filter).add(file);
}
}
}
After that, you should have a map which contain filters and lists of files for which the filter apply. I don't have IDE by hand, so there may be some small mistakes.
Upvotes: 2