如何获取具有指定扩展名且不包括少数目录的文件列表?

How to get list of files with specified extensions and excluding few directories?

我需要列出一个目录中的文件(指定的扩展名),不包括几个子目录。

我可以使用扩展名进行过滤,但不能使用两个条件 1)文件应按扩展名过滤 2) 应排除少数子目录

    File dir = new File("D:\SomeDir");
    String[] extensions = new String[] { "txt", "java" };
    List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
    for (File file : files) {
        System.out.println("file: " + file.getCanonicalPath());
    }

如何排除选中的子目录?

您可以使用 FileUtils.listFilesAndDirs 或其他解决方案: 您可以在第 3 行 List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, *false*); 中排除子目录,并在第二个循环中包含您要列出文件的子目录,而不是列出所有目录并排除一些目录。

给你

public static void main(String[] args) throws IOException {
    File dir = new File("C:\Users\cosmap\Documents\travel-expenses");
    List<String> excludedDirs = Arrays.asList("src", ".git");
    List<String> extensions = Arrays.asList("xml", "yml");

    listFiles(dir, excludedDirs, extensions).forEach(System.out::println);
}

public static List<File> listFiles(File currentFile, List<String> excludedDirs, List<String> extensions) {
    List<File> out = new ArrayList<>();
    File[] files = currentFile.listFiles();

    // might be null
    if(files == null) {
        return out;
    }

    for (File file : files) {
        // add recursively only if is directory and not in the excluded list
        if(file.isDirectory() && !excludedDirs.contains(file.getName())) {
            out.addAll(listFiles(file, excludedDirs, extensions));
        // add if is file and in the allowed extensions list
        } else if (file.isFile() && extensions.contains(file.getName().substring(file.getName().lastIndexOf('.') + 1))) {
            out.add(file);
        }
    }

    return out;
}

试试这个代码:

// for exlude file extension  
NotFileFilter suffixFileFilterFileFilter=new NotFileFilter(new 
SuffixFileFilter(new String[] { "txt", "java" }));  

//to include only selected extension use below one
//IOFileFilter suffixFileFilterFileFilter= new SuffixFileFilter(new String[] { "java", "txt" });

NotFileFilter directoryFileFilterFileFilter=new NotFileFilter(new 
PrefixFileFilter(new String[] { "tolearn", "dir2" }));   // for directory
File dir = new File("D:\SomeDir");
List<File> fileList  = (List<File>)  FileUtils.listFiles(dir,suffixFileFilterFileFilter,directoryFileFilterFileFilter);
    for (File file : fileList) {
        System.out.println("file: " + file.getCanonicalPath());
    }