Re: List of files with given extension in a directory
In article <1250599690.2@user.newsoffice.de>, Hakan <H.L@softhome.net>
wrote:
[...]
public class ExtensionFilter implements FilenameFilter {
protected String pattern;
public Filter (String str) {
pattern = str;
}
public boolean accept (File dir, String name) {
return name.toLowerCase().endsWith(pattern.toLowerCase());
}
}
Thank you for all your help with my question. The FilenameFilter
implementation does what I want, but my boss wants the application to
optionally scan subdirectories of the starting directory as well. The
task is to find all files with an arbitrary extension in this
subtree. How do I extend the code to do that? Thanks in advance.
I use the following recursive algorithm to traverse the directory tree.
The accept() method in your FilenameFilter is usually called by a
FileDialog instance, but there's no reason you can't call it yourself as
you visit entries.
<code>
import java.io.*;
public class ListDir {
public static void main(String args[]) {
File root;
if (args.length > 0) root = new File(args[0]);
else root = new File(System.getProperty("user.dir"));
ls(root);
}
private static void ls(File f) {
File list[] = f.listFiles();
for (File file : list) {
if (file.isDirectory()) ls(file);
else System.out.println(file);
}
}
}
</code>
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>