Listing with Filtration
Home ] Up ] The File Class ] Listing Files and Directories ] [ Listing with Filtration ]

 

 

Listing Directory Contents with a Filter

The list(FilenameFilter filter) form may be used, in combination with an appropriate FilenameFilter, to produce a more selective list. For example, the list could be made to include only those files:

  • whose names begin with "foo", or end in "bar"
  • whose sizes exceed or are smaller than a certain threshold
  • which can be written to
  • any combination of the above

FilenameFilter is an interface.  Its full definition is as follows:

public interface FilenameFilter 
{
    /**
     * Tests if a specified file should be included in a file list.
     *
     * @param dir the directory in which the file was found.
     * @param name the name of the file.
     * @return <code>true</code> if the name should be included in the file
     * list; <code>false</code> otherwise.
     * @since JDK1.0
     */
     boolean accept(File dir, String name);
}

Pretty simple, huh?

Note:

There is a somewhat similar abstract class, javax.swing.filechooser.FileFilter, that relates (as you might expect, given the package) to Swing JFileChooser dialogs.

It might be easy to confuse the FileFilter class with the FilenameFilter interface.

Here's a modification of the previous example to provide filtering of the output so that only certain files are included.  In addition to filtering based on one or more file types, I've also added support for recursive directory searching (including the appropriate indentation so that the output represents the depth of recursion).  I've also removed the need to use any ArrayLists.

package inputOutput;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Properties;

/**
 *  This class finds the current directory, gets a list of all
 *  the files/directories in the current directory, separates
 *  the files from the directories, and prints out the two lists.
 */
public class FilteredDirectoryLister
{
    public static void main(String[] args)
    {
        // Get current directory
        File dir = new File( System.getProperty("user.dir") );
        // Print out its contents, using a filter
        FileTypeFilter filter = new FileTypeFilter( 
                                      new String[] {".xml", ".properties"} );   
        printDirectoryContents(dir, filter, "");
    }
    
    public static void printDirectoryContents(File dir, 
                                              FileTypeFilter filter, 
                                              String indent)
    {
        if (!dir.isDirectory())
            return;
            
        try
        {
            System.out.println(indent + "Directory : '" + 
                                dir.getCanonicalPath() + "'");
            
            // Get the list of directories, using a directory filter
            String[] subdirs = dir.list(m_dirFilter);
            // Recurse through the subdirectories.
            for (String name : subdirs)
            {
              File subdir = new File(name);
              printDirectoryContents(subdir, filter, indent + " ");
            }
            
            // Now, get the list of matching files, using the file type filter
            String[] files = dir.list(filter);
            // Print out the list of files
            for (String name : files)
            {
                System.out.println(indent + " " + name);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    //// Private data ////
    private static DirectoryFilter m_dirFilter = new DirectoryFilter();
}

class FileTypeFilter implements FilenameFilter
{
    FileTypeFilter(String[] types)
    {
        m_types = types;
    }
    
    // Accepts only those files that have one of  
    // the supplied set of file types.
    public boolean accept(File dir, String name)
    {
        boolean includeFile = false;
        File path = new File(dir, name);
        if (path.isFile())
        {
          for (String type : m_types)
          {
            if (name.endsWith(type))
            {
              includeFile = true;
              break;
            }
          }
        }
        return includeFile;
    }
    
    //// Private data ////
    private String[] m_types;
}

class DirectoryFilter implements FilenameFilter
{
    // Accepts any directory
    public boolean accept(File dir, String name)
    {
        boolean includeFile = false;
        File path = new File(dir, name);
        if (path.isDirectory())
          includeFile = true;
        return includeFile;
    }
}

When I ran this from within my NetBeans IDE, it gave me the following output:

Directory : '...\NetBeansProjects\InputOutput'
 Directory : '...\NetBeansProjects\InputOutput\build'
 Directory : '...\NetBeansProjects\InputOutput\dist'
 Directory : '...\NetBeansProjects\InputOutput\nbproject'
  build-impl.xml
  genfiles.properties
  project.properties
  project.xml
 Directory : '...\NetBeansProjects\InputOutput\src'
 Directory : '...\NetBeansProjects\InputOutput\test'
 build.xml

Now, we do see files and directories in the entire hierarchy, and only those files that match the specified filetypes.

 

The page was last updated February 19, 2008