Java code for a recursive directory traversal

Home| Recursive traversal| Level order traversal| Level order traversal with custom list| Traversal with walkFileTree| Traversal with walk
/******************************************************************************/
/*                                                                            */
/*                                              FILE: RecursiveTraversal.java */
/*                                                                            */
/*  Recursive directory traversal in Java                                     */
/*  =====================================                                     */
/*                                                                            */
/*  V1.00   05-JUN-2009   Te          http://www.heimetli.ch                  */
/*                                                                            */
/******************************************************************************/

import java.io.* ;

/**
 * A simple class to demonstrate a recursive directory traversal
 * in Java.
 *
 * Error handling was left out to make the code easier to understand.
 * In production code, you should check if the arguments from the
 * command line are really file files or directories.
 */
public class RecursiveTraversal
{
   /**
    * Works on a single file system entry and
    * calls itself recursively if it turns out
    * to be a directory.
    * @param file A file or a directory to process
    */
   public void traverse( File file )
   {
      // Print the name of the entry
      System.out.println( file ) ;

      // Check if it is a directory
      if( file.isDirectory() )
      {
         // Get a list of all the entries in the directory
         String entries[] = file.list() ;

         // Ensure that the list is not null
         if( entries != null )
         {
            // Loop over all the entries
            for( String entry : entries )
            {
               // Recursive call to traverse
               traverse( new File(file,entry) ) ;
            }
         }
      }
   }

   /**
    * The program starts here.
    * @param args The arguments from the command line
    */
   public static void main( String args[] )
   {
      // Create an object of this class
      RecursiveTraversal rt = new RecursiveTraversal() ;

      if( args.length == 0 )
      {
         // If there are no arguments, traverse the current directory
         rt.traverse( new File(".") ) ;
      }
      else
      {
         // Else process every argument sequentially
         for( String arg : args )
         {
            rt.traverse( new File(arg) ) ;
         }
      }
   }
}
Download Source