如何在Java中查找与通配符字符串匹配的文件? [英] How to find files that match a wildcard string in Java?

查看:23
本文介绍了如何在Java中查找与通配符字符串匹配的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很简单.如果我有这样的字符串:

This should be really simple. If I have a String like this:

../Test?/sample*.txt

那么,获取与此模式匹配的文件列表的普遍接受的方法是什么?(例如,它应该匹配 ../Test1/sample22b.txt../Test4/sample-spiffy.txt 但不匹配 ../Test3/sample2.等等../Test44/sample2.txt)

then what is a generally-accepted way to get a list of files that match this pattern? (e.g. it should match ../Test1/sample22b.txt and ../Test4/sample-spiffy.txt but not ../Test3/sample2.blah or ../Test44/sample2.txt)

我看过org.apache.commons.io.filefilter.WildcardFileFilter,它似乎是正确的野兽,但我不确定如何使用它在相对目录路径中查找文件.

I've taken a look at org.apache.commons.io.filefilter.WildcardFileFilter and it seems like the right beast but I'm not sure how to use it for finding files in a relative directory path.

我想我可以查看 ant 的源代码,因为它使用通配符语法,但我在这里一定遗漏了一些非常明显的内容.

I suppose I can look the source for ant since it uses wildcard syntax, but I must be missing something pretty obvious here.

(编辑:上面的例子只是一个示例.我正在寻找在运行时解析包含通配符的一般路径的方法.我根据mmyers的建议想出了如何去做但这有点烦人.更不用说 java JRE 似乎从单个参数自动解析 main(String[] arguments) 中的简单通配符以节省"我的时间和麻烦......我很高兴我混合中没有非文件参数.)

(edit: the above example was just a sample case. I'm looking for the way to parse general paths containing wildcards at runtime. I figured out how to do it based on mmyers' suggestion but it's kind of annoying. Not to mention that the java JRE seems to auto-parse simple wildcards in the main(String[] arguments) from a single argument to "save" me time and hassle... I'm just glad I didn't have non-file arguments in the mix.)

推荐答案

考虑来自 Apache Ant 的 DirectoryScanner:

Consider DirectoryScanner from Apache Ant:

DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();

您需要引用 ant.jar(对于 ant 1.7.1,大约 1.3 MB).

You'll need to reference ant.jar (~ 1.3 MB for ant 1.7.1).

这篇关于如何在Java中查找与通配符字符串匹配的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆