Java code for a level order directory traversal with a LinkedList
/******************************************************************************/
/* */
/* FILE: StandardList.java */
/* */
/* Level order directory traversal in Java */
/* ======================================= */
/* */
/* V1.00 27-JUL-2009 Te http://www.heimetli.ch */
/* */
/******************************************************************************/
import java.io.* ;
import java.util.* ;
/**
* This class implements a level order traversal of a directory tree.
* It uses the LinkedList collection class to store the Files to be processed.
*/
public class StandardList
{
// The list of Files to be processed
LinkedList<File> list ;
/**
* Initializes the list
*/
public StandardList()
{
list = new LinkedList<File>() ;
}
/**
* Traverses the directory tree in level order (breadth first)
* @param file the first element to be processed
*/
public void traverse( File file )
{
// Add the element to the list
list.add( file ) ;
// Loop until the list is empty
while( list.size() > 0 )
{
// Remove the first element from the list
file = list.remove() ;
// 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 )
{
// Add them to the list
list.add( 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
StandardList sl = new StandardList()) ;
if( args.length == 0 )
{
// If there are no arguments, traverse the current directory
sl.traverse( new File(".") ) ;
}
else
{
// Else process every argument sequentially
for( String arg : args )
{
sl.traverse( new File(arg) ) ;
}
}
}
}