如何在Java中查找与通配符字符串匹配的文件? [英] How to find files that match a wildcard string in 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.blah
或 ../ 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 []参数)从单个参数保存我的时间和麻烦......我很高兴我没有混合中的非文件参数。)
(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屋!