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.
I do it as:
Since Java 8, you can simply use a lambda expression to specify your custom filter:
In the above example, only files with the name "foo" will make it through. Use your own logic of course.
You should override
accept
in the interfaceFilenameFilter
and make sure that the parametername
has only numeric chars. You can check this by usingmatches
:preferably as an instance of an anonymous inner class passsed as parameter to File#list.
for example, to list only files ending with the extension
.txt
:To list only files whose filenames are integers of exactly 2 digits you can use the following in the accept method:
for one or more digits:
EDIT (as response to @crashprophet's comment)
Pass a set of extensions of files to list