猿问

如何获取具有指定扩展名并排除少数目录的文件列表?

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


我可以使用扩展名进行过滤,但不能使用两个条件 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());

    }

如何排除选定的子目录?


小唯快跑啊
浏览 158回答 2
2回答

回首忆惘然

试试这个代码:// for exlude file extension&nbsp;&nbsp;NotFileFilter suffixFileFilterFileFilter=new NotFileFilter(new&nbsp;SuffixFileFilter(new String[] { "txt", "java" }));&nbsp;&nbsp;//to include only selected extension use below one//IOFileFilter suffixFileFilterFileFilter= new SuffixFileFilter(new String[] { "java", "txt" });NotFileFilter directoryFileFilterFileFilter=new NotFileFilter(new&nbsp;PrefixFileFilter(new String[] { "tolearn", "dir2" }));&nbsp; &nbsp;// for directoryFile dir = new File("D:\\SomeDir");List<File> fileList&nbsp; = (List<File>)&nbsp; FileUtils.listFiles(dir,suffixFileFilterFileFilter,directoryFileFilterFileFilter);&nbsp; &nbsp; for (File file : fileList) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("file: " + file.getCanonicalPath());&nbsp; &nbsp; }

慕少森

干得好public static void main(String[] args) throws IOException {&nbsp; &nbsp; File dir = new File("C:\\Users\\cosmap\\Documents\\travel-expenses");&nbsp; &nbsp; List<String> excludedDirs = Arrays.asList("src", ".git");&nbsp; &nbsp; List<String> extensions = Arrays.asList("xml", "yml");&nbsp; &nbsp; listFiles(dir, excludedDirs, extensions).forEach(System.out::println);}public static List<File> listFiles(File currentFile, List<String> excludedDirs, List<String> extensions) {&nbsp; &nbsp; List<File> out = new ArrayList<>();&nbsp; &nbsp; File[] files = currentFile.listFiles();&nbsp; &nbsp; // might be null&nbsp; &nbsp; if(files == null) {&nbsp; &nbsp; &nbsp; &nbsp; return out;&nbsp; &nbsp; }&nbsp; &nbsp; for (File file : files) {&nbsp; &nbsp; &nbsp; &nbsp; // add recursively only if is directory and not in the excluded list&nbsp; &nbsp; &nbsp; &nbsp; if(file.isDirectory() && !excludedDirs.contains(file.getName())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; out.addAll(listFiles(file, excludedDirs, extensions));&nbsp; &nbsp; &nbsp; &nbsp; // add if is file and in the allowed extensions list&nbsp; &nbsp; &nbsp; &nbsp; } else if (file.isFile() && extensions.contains(file.getName().substring(file.getName().lastIndexOf('.') + 1))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; out.add(file);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return out;}
随时随地看视频慕课网APP

相关分类

Java
我要回答