Updated at 2021-06-15 14:01

依赖commons-lang3

    long l = System.currentTimeMillis();
    Set<Path> way2 = new HashSet<>();
    FileUtils.iterateFiles(dir, new String[]{"java"}, true).forEachRemaining(one -> way2.add(one.toPath()));
    System.out.println((System.currentTimeMillis() - l));

依赖jodd-util

    long l = System.currentTimeMillis();
    Set<Path> way1 = new HashSet<>();
    for (File file : FindFile.createWildcardFF().searchPath(dir).recursive(true).includeDirs(false).walking(false)
            .include("**/*.java")) {
        way1.add(file.toPath());
    }
    System.out.println((System.currentTimeMillis() - l));

Java 8原生方式

    l = System.currentTimeMillis();
    try {
        Set<Path> way3 = Files.find(dir.toPath(), Integer.MAX_VALUE,
                (filePath, fileAttr) -> "java".equals(FileNameUtil.getExtension(filePath.toString())))
                .collect(Collectors.toSet());
        System.out.println(way3.size());
    } catch (IOException e) {
        log.error("fail to traverse files", e);
    }
    System.out.println((System.currentTimeMillis() - l));

FileNameUtil来自jodd-util

简单的性能比较

示例项目dir:一个Git本地仓库,共2万多分散在各个层级的Java文件

Java8 Files#find commons-io jodd-util
1 2692 2738 2989
2 2541 2949 3166
3 2492 3303 2961
4 2606 2651 3674
5 2365 2806 3221
6 2568 3048 3502
7 2552 2913 3024
8 2467 2852 2926
9 2726 2671 3482
10 2559 2667 2892
avg 2556.8 2859.8 3183.7

Java 8原生方式的依赖最少,速度在示例情况下最快,是个不错的选择


Java      Java