Regex for directory files

Is it possible to use a regular expression to get file names for files matching a given pattern in a directory without having to manually iterate over all the files.

+7
java regex
source share
3 answers

You can 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 the files that look like this: TXT-20100505-XXXX.trx where XXXX can be any four consecutive digits, do something like this:

 listFilesMatching(new File("/some/path"), "XT-20100505-\\d{4}\\.trx") 
+25
source share

implement FileFilter (it just requires you to override the method

 public boolean accept(File f) 

then each time you request a list of files, jvm will compare each file with your method. A regular expression cannot and should not be used, since java is a cross-platform language and this can cause consequences for different systems.

+1
source share
 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); } } 
0
source share

All Articles