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.
A:
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.
Elijah
2010-05-28 11:57:30
i doubt the validity of the last sentence, why would that be?
n002213f
2010-05-28 12:04:05
Regex is standard across all versions of Java, irrespective of the operating system, it doesn't matter if you use it.
James
2010-05-28 12:52:42
then please tell me how would you distinguish between files and directories on unix and windows with a single regex? I understood that the question was to "get filenames for files matching a given pattern". This reminds me of writing Javascript that supports a few browsers at once...
Elijah
2010-06-02 15:07:11
+7
A:
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")
Bart Kiers
2010-05-28 11:58:40
i have files in the format TXT-20100505-0000.trx where *0000* are changing numbers. TXT-20100525-*\.trx does not evaluate. how would i get such files?
n002213f
2010-05-28 12:09:56
Did you mis-type `TXT-201005525-.*\.trx`? The pattern you wrote will match zero or more `-` followed by `.trx`.
msw
2010-05-28 12:14:44
thanks msw, i hadn't mistyped, my understanding was get all files with prefix `TXT-20100525` followed by any characters then `.trx`. Whats the significant or reason for having the extra `.` before `*\\`
n002213f
2010-05-28 12:20:18
thanks Bart K., however the number can get over 4 digits, i.e. 11111. The best would be any number of integers.
n002213f
2010-05-28 12:30:38