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;
public class FileWildcardMatcher {
static String type = "regex";
static String regexPath = "/home/yhc/workSpace/log/2024/@0.*";
static String globPath = "/home/yhc/workSpace/log/2024/@*[13]";
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());
}
}
public static String pathSplit(String path) {
Matcher matcher = PATH_PATTERN.matcher(path);
while (matcher.find()) {
path = matcher.group();
}
return path;
}
}