I would like to implement a search for files or folders matching a keyword.I am using the following code but the folders returned do not match the string.All the directories are returned.Any ideas what might be wrong please?
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
public class SearchFiles {
public static void main(String args[]){
File directory=new File("C:/Users");
String keyword="Logs";
IOFileFilter fileFilter = new IOFileFilter() {
public boolean accept(File directory, String fileName) {
return directory.isDirectory()&&fileName.contains(keyword);
}
@Override
public boolean accept(File arg0) {
if(arg0.getName().contains(keyword)){return true;}
else{
return false;
}
}
};
List<File> files = (List<File>)FileUtils.listFilesAndDirs(directory, fileFilter, TrueFileFilter.INSTANCE);
for (File file : files) {
try {
System.out.println("file: " + file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
According to javadoc of
FileUtils.listFilesAndDirs, the resulting collection will also include names of the subdirectories themselves. That is the reason why you see the names of the directories in the result.