Recent Post

Categories

Archives

Cow Computing

10 Mar 4

Finding Files with particular extension or Pattern in Java

Often, to find a file with a particular extension or naming pattern within a directory, we might implement as below:

// The directory which search would be conducted
File directoryForSearch = new File("C:\folder");

// This may not be the best way to accomplish the task, please bear me with it
File[] allFile = directoryForSearch.listFiles();
File[] resultFile = new File[allFile.length];
int resultCount = 0;

// loop thru the list of files to find the required files
for(int i=0; i<allFile.length; i++)
{
    if(allFile[i].getName().matches(".*\\.java")
    {
        resultFile[resultCount] = allFile[i];
        resultCount++;
    }
}

Read More / Comment »