在Java中使用glob匹配路径字符串

5

我有以下字符串作为通配符规则:

**/*.txt

并测试数据:

/foo/bar.txt
/foo/buz.jpg
/foo/oof/text.txt

是否可以使用glob规则(而不是将glob转换为正则表达式)来匹配测试数据并返回有效条目?

一个要求:Java 1.6


你想要使用纯Java实现,还是愿意考虑第三方实现? - Boris the Spider
我更喜欢纯Java。但第三方库也可以接受。 - hsz
1
你可以尝试对FileSystem.getPathMatcher进行修改,以适应你的需求。 - Boris the Spider
@BoristheSpider 谢谢。不过它从Java 1.7开始可用 - 我没有提到它 - 我必须使用Java 1.6编译它。 - hsz
它在1.6中不可用(请参见https://dev59.com/gXM_5IYBdhLWcg3wvV5w)。为什么要限制自己使用“glob-to-regex”技术?您还可以使用[wildcard](https://github.com/EsotericSoftware/wildcard)库。 - superbob
3个回答

7
如果您使用的是Java 7,可以使用FileSystem.getPathMatcher
final PathMatcher matcher = FileSystem.getPathMatcher("glob:**/*.txt");

这将需要将您的字符串转换为Path实例:
final Path myPath = Paths.get("/foo/bar.txt");

对于早期版本的Java,你可以尝试使用Apache Commons的WildcardFileFilter。你也可以从Spring的AntPathMatcher中借鉴一些代码-虽然这非常接近于glob-to-regex方法。

很遗憾,我必须使用1.6编译jar。 - hsz

4

FileSystem#getPathMatcher(String) 是一个抽象方法,你不能直接使用它。你需要先获得一个 FileSystem 实例,例如默认实例:

PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");

一些例子:
// file path
PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
m.matches(Paths.get("/foo/bar.txt"));                // true
m.matches(Paths.get("/foo/bar.txt").getFileName());  // false

// file name only
PathMatcher n = FileSystems.getDefault().getPathMatcher("glob:*.txt");
n.matches(Paths.get("/foo/bar.txt"));                // false
n.matches(Paths.get("/foo/bar.txt").getFileName());  // true

3

补充之前的回答:使用来自Apache commons-lang库的org.apache.commons.io.FilenameUtils.wildcardMatch(filename, wildcardMatcher)函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接