You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 如何递归获取所有包含.java文件的目录路径

实现思路

核心逻辑是递归遍历所有层级目录,对每个目录执行如下判断:

  • 当前目录下直接存在.java后缀的文件,就将当前目录路径存入结果集
  • 继续递归遍历当前目录的所有子目录,重复上述检查逻辑
  • 最终结果可根据需求统一转为全大写、格式化路径分隔符

核心逻辑验证

完全匹配你给出的两个示例要求:

  • 示例1中Foo3目录下没有直接存放Java文件,只有子目录Foo4有,因此结果不会返回FOO/FOO3
  • 示例2中Foo3目录下直接存放了ipsum.java,因此FOO/FOO3会被加入结果集,同时其子目录Foo4也符合要求会被返回

Java 实现代码(基于NIO)

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class JavaDirFinder {
    public static List<String> findDirsWithJavaFiles(Path rootDir) throws IOException {
        List<String> result = new ArrayList<>();
        Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                // 检查当前目录是否存在.java文件
                boolean hasJavaFile = Files.list(dir)
                        .anyMatch(path -> Files.isRegularFile(path) && path.getFileName().toString().endsWith(".java"));
                if (hasJavaFile) {
                    // 转全大写并统一用/作为路径分隔符
                    String formatPath = dir.toString().toUpperCase().replace('\\', '/');
                    result.add(formatPath);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        return result;
    }

    public static void main(String[] args) throws IOException {
        // 替换为实际的根目录路径
        Path root = Path.of("你的根目录路径/Foo");
        List<String> dirs = findDirsWithJavaFiles(root);
        dirs.forEach(System.out::println);
    }
}

Python 实现代码(更简洁)

import os

def find_dirs_with_java_files(root_path):
    result = []
    for dirpath, _, filenames in os.walk(root_path):
        # 检查当前目录下是否有.java文件
        if any(f.endswith('.java') for f in filenames):
            # 转全大写并统一用/作为路径分隔符
            format_path = dirpath.replace('\\', '/').upper()
            result.append(format_path)
    return result

# 调用示例
if __name__ == '__main__':
    root = "你的根目录路径/Foo"
    print(find_dirs_with_java_files(root))

注意事项

  • 如果不需要输出全大写路径,去掉代码中的.toUpperCase()/.upper()调用即可
  • 如果需要保留系统原路径分隔符,删除对应的replace逻辑即可
  • 两种实现都支持任意层级的嵌套目录,不需要额外调整适配嵌套深度

内容的提问来源于stack exchange,提问作者kimbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:09:01