Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java filter file by name and extension

i’m developing a little Java program for my company.
In this program i need to retreive from my local folder some files, but i need to search the files by the first three character and by extension.
Reading the java documentation I saw that the java.nio.file.Files library exists and So to filter the files by name and extension I saw that there are the startsWith() and endsWith() constructs which I have implemented as follows so I tried to use it.

//recuperiamo tutti i file nella directory attuale e filtro per F4_*.cbi, CN_*.cbi, A4_*.cbi, Q4_*.cbi
            dirFiles = new File("C:/www/htdocs/comune/F24_CT/deleghe_da_inviare_a_icbpi/");
            listOfFiles = dirFiles.listFiles(new FilenameFilter() { 
                    public boolean accept(File dirFiles, String filename)
                         {
                                return filename.startsWith("F4_");
                        }
            } );

Is it possible to filter for various filenames and concatenate endsWith tostartsWith?

I would like to be able to filter by name according to the criteria startsWits("F24 _"), startsWith("CN _"), startsWith("A4 _") and endsWith(".txt ").

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I accept any advice or suggestions to improve my knowledge and the code

>Solution :

You could either use a logical AND expression && or a regex.

listOfFiles = dirFiles.listFiles(new FilenameFilter() {
    public boolean accept(File dirFiles, String filename) {
        boolean endsWith = filename.toLowerCase().endsWith(".txt");
        boolean startsWith = filename.startsWith("F4_") && filename.startsWith("CN_") && filename.startsWith("A4_") && filename.startsWith("Q4_");
        return startsWith && endsWith;
    }
});

If you want to use a regex it will looks like this (F4_|CN_|A4_|Q4_).*(\.txt|\.TXT).
You can check how this regex works here.

listOfFiles = dirFiles.listFiles(new FilenameFilter() {
    public boolean accept(File dirFiles, String filename) {
        return filename.matches("(F4_|CN_|A4_|Q4_).*(\.txt|\.TXT)");
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading