简体   繁体   English

如何获取不包括某些子目录的所有子目录?

[英]How to get all subdirectories excluding some subdirectories?

I have a list of directories that I'm using in a selectMenu in a webpage.我有一个我在网页的 selectMenu 中使用的目录列表。

The list contains all sub-directories under a certain directory, retrieved using the below java code..该列表包含某个目录下的所有子目录,使用以下 java 代码检索..

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).我想过滤 myDirectories 列表以排除不包含某个文件(例如称为 testFolder)的子目录。 In other words, I want myDirectories to include only files that have a subfolder called testForder.换句话说,我希望 myDirectories 仅包含具有名为 testForder 的子文件夹的文件。 How to do that?怎么做?

I guess, you have to implement your own FileFilter.我想,您必须实现自己的 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.说明:对于来自C:\\myHomeDirectory 的每个文件进行测试,如果给定的文件是目录。 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如果找到此类文件,则允许该目录成为myDirectories 的一部分

I have no chance to test if this example code compiles now, but I hope it helps you to get your solution.我现在没有机会测试此示例代码是否可以编译,但我希望它可以帮助您获得解决方案。

I found all the FileNameFilter stuff with subdirs a bit complex.我发现所有带有子目录的 FileNameFilter 东西都有些复杂。 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();
       ...
   } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM