Exclude specific sub-directories using apache commons fileutils

只愿长相守 提交于 2021-02-10 12:42:56

问题


I want to list all the files under current directory but excluding all the files within the subdirectory and it's subdirectories using apache commons lib.

For Example : If my current directory is -- A and its subdirectory as B, C ,D
B having subdirectory as b1,b2 (b1 has b12 as its subdirectory) and C having c1 , c2... now I want to list all the files in C,c1,c2, D (excluding B , b1 ,b12 , b2 )

Any help will be highly appreciated!


回答1:


Use org.apache.commons.io.FileFilter, there's a good example of how to use it in the JavaDoc.

For example I have a directory structure like:

/tmp/testFilter/A
/tmp/testFilter/B
/tmp/testFilter/C/c1
/tmp/testFilter/C/c2
/tmp/testFilter/D/d1

Then I could list only the files under C and D with the following code:

public class FileLister {
    public static void main(String args[]) {
        File dir = new File("/tmp/testFilter");
        String[] files = dir.list(
            new NotFileFilter(
                new OrFileFilter(
                        new PrefixFileFilter("A"),
                        new PrefixFileFilter("B")
                )
            )
        );
        listFiles(dir, files);
    }

    private static void listFiles(File rootDir, String[] files) {
        for (String fileName: files) {
            File fileOrDir = new File(rootDir, fileName);
            if (fileOrDir.isDirectory()) {
                listFiles(fileOrDir, fileOrDir.list());
            } else {
                System.out.println(fileOrDir);
            }
        }
    }
}



回答2:


IOFileFilter fileFilter1 =   FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("A", null));
IOFileFilter fileFilter2 =   FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("B", null));
FileFilter fileFilter =   FileFilterUtils.and(fileFilter1, fileFilter2 );
List<File> files =  (List<File>)FileUtils.listFilesAndDirs(dir ,TrueFileFilter.INSTANCE ,(IOFileFilter)fileFilter );
 for (int i = 0; i < files.size(); i++) {
  System.out.println(files.get(i));
}


来源:https://stackoverflow.com/questions/20658841/exclude-specific-sub-directories-using-apache-commons-fileutils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!