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

如何用Java递归匹配路径/正则表达式查找符合条件的文件?

实现方案

推荐直接使用JDK7及以上版本原生提供的PathMatcher + 文件遍历API,标准无第三方依赖,完美覆盖你的需求:

核心优势

  • 原生JDK实现,无需引入额外依赖
  • 同时支持glob通配符语法、正则表达式两种匹配规则
  • 天然支持绝对路径匹配、单文件精确匹配、递归目录匹配

代码实现

import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;

public class FileMatcher {
    public static List<Path> matchFiles(String pattern) throws IOException {
        // 自动识别匹配规则类型,默认用glob,也可切换为regex正则模式
        PathMatcher matcher = FileSystems.getDefault()
                .getPathMatcher("glob:" + pattern);
        List<Path> matchedFiles = new ArrayList<>();

        // 解析匹配路径的根目录,避免全磁盘扫描
        Path rootPath;
        int wildcardIndex = Math.min(
                pattern.indexOf('*'),
                pattern.indexOf('?')
        );
        if (wildcardIndex == -1) {
            // 没有通配符,直接判断单文件是否存在
            Path singleFile = Paths.get(pattern);
            if (Files.exists(singleFile) && Files.isRegularFile(singleFile)) {
                matchedFiles.add(singleFile);
            }
            return matchedFiles;
        } else {
            // 截取通配符之前的路径作为扫描根目录
            rootPath = Paths.get(pattern.substring(0, wildcardIndex)).getParent();
            if (rootPath == null || !Files.exists(rootPath)) {
                return matchedFiles;
            }
        }

        // 递归遍历根目录,过滤匹配的文件
        Files.walk(rootPath)
                .filter(Files::isRegularFile)
                .filter(matcher::matches)
                .forEach(matchedFiles::add);

        return matchedFiles;
    }

    public static void main(String[] args) throws IOException {
        // 测试场景1:匹配子目录下的png
        List<Path> files1 = matchFiles("C:\\Users\\me\\Desktop\\project\\src\\test\\resources\\screenshots\\*\\*.png");
        // 测试场景2:匹配单个文件
        List<Path> files2 = matchFiles("C:\\Users\\me\\Desktop\\project\\src\\test\\resources\\screenshots\\first.png");
    }
}

备选方案(Spring生态适配)

你之前用的Spring PathMatchingResourcePatternResolver 也可以实现绝对路径匹配,只需要给路径前缀加上file:即可,不需要自己实现遍历逻辑:

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 路径加file:前缀即可扫描文件系统绝对路径,不会限制在classpath下
Resource[] resources = resolver.getResources("file:C:/Users/me/Desktop/project/src/test/resources/screenshots/*/*.png");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 01:57:02