Reputation: 7937
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.
Upvotes: 11
Views: 30158
Reputation: 170148
You could use 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:
listFilesMatching(new File("/some/path"), "XT-20100505-\\d{4}\\.trx")
EDIT
Starting with Java8 the complete 'return'-part can be written with a lamda-statement:
return root.listFiles((File file) -> p.matcher(file.getName()).matches());
Upvotes: 29
Reputation: 1
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);
}
}
Upvotes: 0
Reputation: 19810
implement FileFilter (just requires that you override the method
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.
Upvotes: 1