Home > Blockchain >  Java filter file by name and extension
Java filter file by name and extension

Time:11-29

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 ").

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

CodePudding user response:

Make is simple and split the 2 rules, and use logic operators

boolean isValidStart = 
        filename.startsWith("F24 _") || 
        filename.startsWith("CN _") || 
        filename.startsWith("A4 _");
  
boolean isTxt = filename.endsWith(".txt");
            
return isValidStart && isTxt;

CodePudding user response:

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