How to get all subdirectories excluding some subdirectories?

2.6k views Asked by At

I have a list of directories that I'm using in a selectMenu in a webpage.

The list contains all sub-directories under a certain directory, retrieved using the below java code..

File directory = new File("C:\\myHomeDirectory");
myDirectories = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);

I want to filter the list of myDirectories to exclude subdirectories which do NOT contain a certain file(say called testFolder). In other words, I want myDirectories to include only files that have a subfolder called testForder. How to do that?

2

There are 2 answers

0
Jiri Kusa On BEST ANSWER

I guess, you have to implement your own FileFilter.

Something like this:

 class CustomDirectoryFilter implements FileFilter {

private String allowedFileName = "testFolder";

  @Override
  public boolean accept(File pathname) {

    if (pathname.isDirectory()) {
      File[] subFiles = pathName.listFiles();
      for (File file : subFiles){
        if (file.getName().equals(allowedFileName)){
           return true;
        }
      }
    }
    return false; 
  }
}

Explanation: for each file from C:\myHomeDirectory test if given file is directory. If it is, get array of all files in it and test, if any of these files contains your file. If such file found, allow the directory to be part of myDirectories

I have no chance to test if this example code compiles now, but I hope it helps you to get your solution.

0
Roland Roos On

I found all the FileNameFilter stuff with subdirs a bit complex. I use this now:

FileUtils.iterateFiles(rootdir, filefilter, dirfilter);

  <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
        <type>jar</type>
   </dependency>

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import java.util.Iterator;

   File inputDir = new File(inputPath.toString());
   Iterator<File> matchesIterator = FileUtils.iterateFiles(
            inputDir, new WildcardFileFilter("somefilenamefilter*.xml"), TrueFileFilter.TRUE);
   while (matchesIterator.hasNext()) {
       File someFile = matchesIterator .next();
       ...
   }