'FilenameFilter for several files

I have a folder where excel files are stored. The files always start with Template HP_x.xlsx (x stands for additional information). With a loop I have already read the path and the name of the file. Unfortunately it reads out all xlsx files. How can I use the filenamefilter so that it only reads out the Template_HP...xlsx files?

Thank you :).



Solution 1:[1]

You could check the start of the filename and the extension, something like this:

... new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        boolean checkStart = filename.toLowerCase().startsWith("Template_HP_");
        boolean checkEnd = filename.toLowerCase().endsWith(".xlsx");
        return (checkStart && checkEnd);
    }
} ...

Or, optimized..

... return ((filename.toLowerCase().startsWith("Template_HP_")) && (filename.toLowerCase().endsWith(".xlsx"))); ...

The code just checks if the string containing the filename starts with Template_HP_ and ends with the correct extension, .xlsx. If so, it returns true, otherwise false.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1