Finding subdirs matching a given name
I need to find dirs having a given name (I'll call it "fixedname") under a root dir. I have the following dir structure:
- rootdir
-- someName1
--- fixedName
-- somename2
--- fixedName
Under the root dir there are some dirs which name is unknow, and under those dirs there are my target dirs. The result of my "find" should be: [rootDir/someName1/fixedName, rootDir/someName2/fixedName]
I tried using Commons FileUtils, specifically the method listfiles, doing the following:
final File ROOTDIR = new File("/rootdir");
IOFileFilter nameFilter = new NameFileFilter("fixedName");
Collection<File> files = FileUtils.listFiles(ROOTDIR, TrueFileFilter.TRUE, nameFilter);
but it doesn't work, since the subdir walk stops at the level of someName* dirs. I could write a custom method, but I was wondering whet开发者_如何转开发her one can achieve what I need using Commons FileUtils or the Java API (using some high level function, I mean)
I'd have just done it manually with the File class, something like:
java.util.List<File> result = new ArrayList<File>();
final String searchFor = "fixedName";
for (File child : f.listFiles()) {
result.addAll(Arrays.asList(
child.listFiles(new FilenameFilter() {
public boolean accept(File parent, String childName) {
return childName.equals(searchFor);
}
}
)));
}
I haven't personally used this function but from looking at the API, I think you're interpreting the method arguments incorrectly.
listfiles takes a root directory, a file filter and a directory filter. The directory filter is for determining which sub-directories to look in, not for finding directories. You want to look for "fixedName" within All sub-directories. I think you actually want to call the method like this:
final File ROOTDIR = new File("/rootdir");
IOFileFilter nameFilter = new NameFileFilter("fixedName");
Collection<File> files =
FileUtils.listFiles(ROOTDIR, nameFilter, TrueFileFilter.INSTANCE);
精彩评论