Friday, December 1, 2006

File find in Java

The other day I wanted to search a directory and get a list of files that match a pattern. Basically the find command. I was very annoyed that Java didn't have anything like this built into the File API. So this little method does the trick. You might use it like


findFiles(new File("/home/blambi/workspace"),
File.separator,
".*\\.class");


to find all the class files in /home/blambi/workspace.


/**
* Recursively searches a directory for filenames matching pattern and
* uses delim as the file seperator.
* @param dir dir to search
* @param delim file seperator
* @param pattern string to match against
* @return a list of strings that are the filenames that match pattern
*/
List<String> findFiles(File dir, String delim, String pattern)
{
List<String> ls = new ArrayList<String>();
String[] dirs = dir.list();
for (String x:dirs)
{
File tmp = new File(dir,x);
if (tmp.isDirectory())
{
List<String> fs = findFiles(tmp,delim,pattern);
for (String y:fs)
{
ls.add(x + delim + y);
}
}
else if (x.matches(pattern))
{
ls.add(x);
}
}
return ls;
}

No comments: