I need to search a text in all the files of a directory and subdirectorys any clever idea ?
+4
A:
Use the org.apache.commons.io.FileUtils.iterateFiles()
method from Apache commons-io
From the javadoc:
Allows iteration over the files in a given directory (and optionally its subdirectories) which match an array of extensions.
For example:
Iterator iter = FileUtils.iterateFiles(directory,
new String[]{"txt","java"}, true);
while(iter.hasNext()) {
File file = (File) iter.next();
searchInFile(file);
}
Rich Seller
2009-09-21 16:25:55
+1
A:
Try a class with a recursive method something like this:
public class Searcher {
private String toFind, toReplace;
// whatever other info you need
public void searchInTextFiles(File dir) {
File[] a = dir.list();
for (File f : a) {
if (f.isDirectory()) {
searchInTextFiles(f);
} else if (f.name().endsWith(".txt")) {
searchInFile(f);
}
}
}
private void searchInFile(File f) {
// do whatever you need to do on f using fields from this class
}
}
David Tinker
2009-09-21 16:28:02
A:
//edit u have to define CheckFile funct...
void Found(String dir,Vector flist){
File srchdir(dir);
File[] listf=listFiles();
for(int i=0;i<srchdir.listf.length;i++){
if(listf[i].isDirectory()){ Found(dir+"/"+listf[i].getName(),flist);
}else{ if(CheckFile(listf[i])) flist.add(dir+"/"+listf[i].getName()); }
}
}
Vector Found(String dir){
File srchdir(dir);
Vector flist=new Vector();
File[] listf=listFiles();
for(int i=0;i<srchdir.listf.length;i++){
if(listf[i].isDirectory()){ Found(dir+"/"+listf[i].getName(),flist);
}else{ if(CheckFile(listf[i])) flist.add(dir+"/"+listf[i].getName()); }
}
return flist;
}
n00b32
2009-09-21 16:30:04
+1 because, haha
instanceofTom
2009-09-21 17:35:19
+1, but should be new String[]{"-r"}nice example
Alex Ivasyuv
2010-03-30 15:30:27