Click to See Complete Forum and Search --> : find files in subdirectories....


athanach
12-04-2007, 05:30 PM
i want to find and take all the files from a directory but from the subdirectories
i use the program below but i t gives me the files from the directory i give only no the subdirectories.

Any help for taking and the files from subdirectories???

import java.io.File;
import java.io.FilenameFilter;
import java.lang.String;
import java.lang.Exception;
import javax.swing.filechooser.FileFilter;


public class filesFinder {

/** Creates a new instance of fileFinder */
public void Finder(File dir) {




FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.endsWith(".meta");
}
};



String[] files = dir.list(filter);
//File[] files = dir.listFiles();


//files = dir.listFiles();

if (files == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<files.length; i++) {
// Get filename of file or directory
String filename = files[i];
System.out.println(filename);
}


}


}

public static void main(String[] args) {

File dir=new File("sas");

filesFinder g=new filesFinder();
g.Finder(dir);
}

}

mdjo
12-05-2007, 01:20 PM
I'm typing this code of the top of my head, so it may have syntax errors, etc, but the principle would be something like this:


void findSubFiles(File dir)
{
File[] files=dir.listFiles();
for (int x=0;x<files.length;++x)
{
if (files[x].isDirectory())
findSubFiles(files[x]);
else if (isInteresting(files[x]))
processFile(files[x]);
}
}


isInteresting is a placeholder for where you decide that this is a file you want to process.

processFile would then do whatever needs to be done with an interesting file.

This function calls itself recursively, so it will go through as many directory levels as you have looking for interesting files.

Note that using filters in this context is tricky, because the filter would be applied against both directories and files, which probably isn't what you want. You're better to just examine each file name you get back in the isInteresting() function.