Hi i want to recursively check if the files and subfolders of a certain directory contain a certain string so tried this
package com.tecsys.sm.test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import com.tecsys.sm.util.WindowsDirectories;
public class ApacheListOfFiles {
public static void main(String[] args){
final String envName= "test_trunkcpsm";
WindowsDirectories wd = new WindowsDirectories();
File startPath = new File(wd.getStartMenuDir()+File.separator+"Programs");
Collection<File> listF = FileUtils.listFiles(startPath, new IOFileFilter() {
@Override
public boolean accept(File dir, String name) {
return false;
}
@Override
public boolean accept(File file) {
// TODO Auto-generated method stub
if(file.getName().contains(envName)){
System.out.println(file);
return true;
}else
return false;
}
},TrueFileFilter.INSTANCE);
System.out.println(listF.size());
Iterator<File> it = listF.iterator();
while(it.hasNext()){
System.out.println("Le fichier est : "+it.next());
}
}
}
The output of this is the following:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\TECSYS\iTopia Environments\test_trunkcpsm 0
So he finds the file i am searching for but still return an empty list, why is that ? And also while we are at it, when is the first accept called ? i have some difficulties understanding how this class works.
It works for me, may be the reason is false
returned in the first accept()
.
You may also want to look at DelegateFileFilter
to implement a single accept()
.
Or to use this single call for the job:
Collection listF = FileUtils.listFiles(
startPath, new WildcardFileFilter("*" + envName + "*"), TrueFileFilter.TRUE);