javafilefilterjava.nio.file

Java filter file by name and extension


I'm developing a little Java program for my company. In this program I need to retrieve 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 ").

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)");
        }
    });