Link to home
Start Free TrialLog in
Avatar of maruthi123
maruthi123

asked on

Pattern Based file listing of a directory in java

Hi

I want to list files in a directory based on a pattern.
The FilenameFilter Interface is used for that.

eg:
import java.io.FilenameFilter;
import java.io.File;

class JavaSrcFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith("*.java"));
    }
}

class Main {
    public static void main (String[] args) {
        String dir = ".";
        if (args.length == 1)
            dir = args[0];

        File f1 = new File(dir);
        int i;
        String[] ls;
        FilenameFilter filter = new JavaSrcFilter();
        System.out.println("Java Source Files: " );
        for (ls = f1.list(filter), i = 0;
             ls != null && i < ls.length;
             System.out.println("\t" + ls[i++]));
    }
}

But the above just checks for some particular condition like files ending with .java
 
Any help is greatful in making it generalised such that it works for patterns like
a. *.*
b. *a?b.*
c.  [abc]?*

i.e accepting all types of possible patterns

thanking you in advance
maruthi.ch


Avatar of Venci75
Venci75

if you use java 1.4, that accept method could be like this:
return (name.matches("reg exp"));
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
maruthi123:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.