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++;
    }
}

In fact, there is a more convenient way to get the above task done. It’s not hard at all, however people might have often omitted it. We shall make use of “FilenameFilter” to filter the files instead of looping.

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

// Using FilenameFilter to do the filtering job
File[] resultFile = directoryForSearch.listFiles(new FilenameFilter()
{
    public boolean accept(File dir, String name)
    {
        // Here we try to match file with extension ".java"
        // Returning YES/TRUE indicate the acceptance of the file else ignore
        return name.matches(".*\\.java");
    }
}

This code reduction and performance improvement would definitely help when one is trying to implement a complex file search.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • StumbleUpon
  • Twitter

No Comments »

No comments yet.

Leave a comment