Java 目录中文件的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2928680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for files in a directory
提问by n002213f
Is it possible to use a regular expression to get filenames for files matching a given pattern in a directory without having to manually loop through all the files.
是否可以使用正则表达式来获取目录中与给定模式匹配的文件的文件名,而无需手动遍历所有文件。
采纳答案by Bart Kiers
You could use File.listFiles(FileFilter)
:
你可以使用File.listFiles(FileFilter)
:
public static File[] listFilesMatching(File root, String regex) {
if(!root.isDirectory()) {
throw new IllegalArgumentException(root+" is no directory.");
}
final Pattern p = Pattern.compile(regex); // careful: could also throw an exception!
return root.listFiles(new FileFilter(){
@Override
public boolean accept(File file) {
return p.matcher(file.getName()).matches();
}
});
}
EDIT
编辑
So, to match files that look like: TXT-20100505-XXXX.trx
where XXXX
can be any four successive digits, do something like this:
因此,要匹配如下文件:TXT-20100505-XXXX.trx
whereXXXX
可以是任意四个连续数字,请执行以下操作:
listFilesMatching(new File("/some/path"), "XT-20100505-\d{4}\.trx")
回答by Elijah Saounkine
implement FileFilter (just requires that you override the method
实现 FileFilter(只需要您覆盖该方法
public boolean accept(File f)
then, every time that you'll request the list of files, jvm will compare each file against your method. Regex cannot and shouldn't be used as java is a cross platform language and that would cause implications on different systems.
然后,每次您请求文件列表时,jvm 都会将每个文件与您的方法进行比较。不能也不应该使用正则表达式,因为 java 是一种跨平台语言,这会导致对不同系统的影响。
回答by hanisa
package regularexpression;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularFile {
public static void main(String[] args) {
new RegularFile();
}
public RegularFile() {
String fileName = null;
boolean bName = false;
int iCount = 0;
File dir = new File("C:/regularfolder");
File[] files = dir.listFiles();
System.out.println("List Of Files ::");
for (File f : files) {
fileName = f.getName();
System.out.println(fileName);
Pattern uName = Pattern.compile(".*l.zip.*");
Matcher mUname = uName.matcher(fileName);
bName = mUname.matches();
if (bName) {
iCount++;
}
}
System.out.println("File Count In Folder ::" + iCount);
}
}