Search code examples
javafileutilsapache-commons-iofilefilter

How to get all subdirectories excluding some subdirectories?


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?


Solution

  • 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.