CS2
Recursion
11
Directory Listing
nHere’s a sample recursive method for non-numerical application. The routine lists the names of all files in a given directory and its subdirectories.
public void directoryListing( File dir )
{
//assumption: dir represents a directory
String[] fileList = dir.list();  //get the contents
String   dirPath = dir.getAbsolutePath();

for (int i = 0; i < fileList.length; i++) {

File file = new File( dirPath + "\\" + fileList[i] );

if ( file.isFile() ) {   //it’s a file


System.out.println( file.getName() );
}
else {

directoryListing( file ); //it’s a directory
}     //so recurse
}
}
Recursive case
End case
Test
In pseudocode the above method is expressed as follows:

public void directoryListing( File dir )
{
   //assumption: dir represents a directory
   fileList = an array of names of files and
         subdirectories in the directory dir;

   for (each element in fileList) {
     if (an element is a file) {
       output the element’s filename;  //end case: it’s                            //a file.
     }
     else { //recursive case: it’s a directory
       call directoryListing with element as an argument;
      }
   }
}