Use of FilenameFilter

Leem.fin picture Leem.fin · Nov 12, 2013 · Viewed 43.5k times · Source

I have a directory:

File dir = new File(MY_PATH);

I would like to list all the files whose name is indicated as integer numbers strings, e.g. "10", "20".
I know I should use:

dir.list(FilenameFilter filter);

How to define my FilenameFilter?

P.S. I mean the file name could be any integer string, e.g. "10" or "2000000" or "3452345". No restriction in the number of digits as long as the file name is a integer string.

Answer

Maroun picture Maroun · Nov 12, 2013

You should override accept in the interface FilenameFilter and make sure that the parameter name has only numeric chars. You can check this by using matches:

String[] list = dir.list(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.matches("[0-9]+");
    }
});