Listing 11: ListSomeFiles.java — Uses a FilenameFilter to list only certain files

import java.io.*;
import java.util.*;
import java.text.*;

class ListSomeFiles
{
   static int indentLevel = 0;
   static String suffix = null;
    
   public static void main(String[] args)
      throws IOException
   {
      suffix = args[0];
      list(new File(
         System.getProperty("user.dir")));
   }

   static void list(File dir)
      throws IOException
   {
      ++indentLevel;
      File[] files = 
         dir.listFiles(new SuffixFilter());
      for (int i=0; i < files.length; ++i)
      {
          display(files[i].getName());
          if (files[i].isDirectory())
              list(files[i]);
      }
      --indentLevel;
   }
    
  static void display(String name)
  {
     for (int i = 0; i < indentLevel; ++i)
        System.out.print("    ");
     System.out.println(name);
  }
    
  static class SuffixFilter 
     implements FilenameFilter
  {
     public boolean 
     accept(File dir, String name)
     {
        return name.endsWith(suffix);
     }
   }
}

/* Output from 'ListSomeFiles .java':
    Employee.java
    FileViewer.java
    FindFile.java
    ListAllFiles.java
    ListFiles.java
    ListSomeFiles.java
    ListZip.java
    LogFile.java
    LogFileTest.java
    ProcessRecords.java
    PropTest.java
    Stack.java
    Test.java
    ViewFile.java
*/
— End of Listing —