Java directory list - list all files matching a filename pattern

Java file and directory FAQ: How do I get a list of all files in a directory that match a certain filename pattern?

For a recent Java project I needed to be able to get a list of files within a directory that matched a specific filename pattern. In this case, I needed a list of all files in a directory that began with the underscore character (_). This is relatively easy in Java; as usual it's just hard to find a good example.

Here's the sample code taken directly from my application. Only the relevant methods are shown:

  public void printUIComponents()
  {
    String[] listOfFilesToParse = getListOfJSPTemplatesToParse(_jspTemplateDir);
    for ( int i=0; i<listOfFilesToParse.length; i++ )
    {
      String templateName = listOfFilesToParse[i];
      String outputFileSuffix = removeLeadingUnderscore(templateName);
      parseJspTemplate( templateName, outputFileSuffix );
    }
  }

  // returns a string array that is a list of all
  // filenames that match the desired filename pattern
  String[] getListOfJSPTemplatesToParse(String aDirectory)
  {
    // our filename filter (filename pattern matcher)
    class OnlyUnderscoreFilter implements FilenameFilter
    {
      public boolean accept(File dir, String s)
      {
        if ( s.startsWith("_") ) return true;
        return false;
      }
    }
    return new java.io.File(aDirectory).list( new OnlyUnderscoreFilter() );
  }

The action starts in the printUIComponents method, which quickly calls the getListOfJSPTemplatesToParse method, passing in a directory name. This method uses an inner class named OnlyUnderscoreFilter that implements the FilenameFilter interface. At that point all I had to do was implement the accept method of that interface, and I was ready to go.

Everything else besides that is pretty standard stuff; the really important part was knowing that I needed to use File and then implement the FilenameFilter interface.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.