【Java文件管理】关于路径里含有通配符或者正则的筛选方法

1. 参数

参数名含义默认值
type类型,支持regex(正则表达式)或者glob(通配符)regex
regexPath路径,支持正则表达式(正则表达式必须以/@开头,需要放在路径的前面,禁止出现/xxxx/x@.*这样的路径)/home/yhc/workSpace/log/2024/@0.*
globPath路径,支持通配符(通配符必须以/@开头,需要放在路径的前面,禁止出现/xxxx/x@.*这样的路径)/home/yhc/workSpace/log/2024/@*[13]
PATH_PATTERN路径截取器(必须以/@开头,需要放在路径的前面,禁止出现/xxxx/x@.*这样的路径)Pattern.compile(“^((?!/@).)*”)

2. 代码

package com.api.apidemo.tool.file;

import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author yhc
 * @description: 文件通配符匹配器,支持正则表达式和通配符
 */
public class FileWildcardMatcher {

    /**
     * 类型,支持regex(正则表达式)或者glob(通配符)
     */
    static String type = "regex";
    /**
     * 路径,支持正则表达式(正则表达式必须以/@开头,需要放在路径的前面,禁止出现/xxxx/x@.*这样的路径)
     */
    static String regexPath = "/home/yhc/workSpace/log/2024/@0.*";
    /**
     * 路径,支持通配符(通配符必须以/@开头,需要放在路径的前面,禁止出现/xxxx/x@.*这样的路径)
     */
    static String globPath = "/home/yhc/workSpace/log/2024/@*[13]";
    /**
     * 路径截取器(必须以/@开头,需要放在路径的前面,禁止出现/xxxx/x@.*这样的路径)
     */
    static Pattern PATH_PATTERN = Pattern.compile("^((?!/@).)*");

    public static void main(String[] args) {
        fileWildcardMatcher();
    }

    /**
     * 文件通配符匹配器
     */
    private static void fileWildcardMatcher() {
        String filePath;
        if ("regex".equals(type)) {
            filePath = regexPath;
        } else {
            filePath = globPath;
        }
        String path = pathSplit(filePath);
        PathMatcher matcher = FileSystems.getDefault().getPathMatcher(type + ":" + filePath.replace("@", ""));
        Path directory = Paths.get(path);
        List<Path> files = null;
        try {
            files = Files.walk(directory)
                    .filter(matcher::matches)
                    .collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for (Path file : files) {
            System.out.println(file.toAbsolutePath());
        }
    }

    /**
     * 解析路径,获取日期
     *
     * @param path 路径
     * @return 截取后/@的路径,没有找到有效的日期则返回原路径
     */
    public static String pathSplit(String path) {
        Matcher matcher = PATH_PATTERN.matcher(path);
        while (matcher.find()) {
            path = matcher.group();
        }
        // 没有找到有效的日期
        return path;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值