Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java: Complete the method listDirectories below. This method should recursively

ID: 3590049 • Letter: J

Question

Java:

Complete the method listDirectories below. This method should recursively search for, and print, the names of all subdirectories existing beneath the directory entered by the user. If there are no subdirectories beneath the point where the program begins (represented by the parameter: directory), the method should print "No Directories."

Strategy: Use the methods of the File class to handle the task. The method should get a list of all files in the directory passed through the parameter. The method should then loop through the list. If the file being examined is a directory, then the method should print the name of the directory and recursively call itself with the new directory as the parameter. Watch out that you send the correct pathname!!!

Explanation / Answer

import java.io.*;

public class DirectoryList {

    /**
     * Read in a directory name entered by the user
     * and print out a recursive list of directories
     *
     * @param args The command line arguments
     */
    public static void main ( String[] args ) throws IOException {

        BufferedReader keyboard = new BufferedReader
          ( new InputStreamReader( System.in ) );
        String userInput = "";

        System.out.print ( "Enter the name of a directory: " );
        userInput = keyboard.readLine();

        listDirectories( userInput );
    }

    /**
     * Using recursion, print out all subdirectories beneath the
     * directory sent in the parameter
     *
     * @param directory The name of the directory to begin search
     */
    public static void listDirectories ( String directory ) {

        File dirFile = new File( directory );
        File[] fileList = dirFile.listFiles();
        for (File file : fileList) {
            if (file.isFile()) {
                System.out.println(file.getAbsolutePath());
            } else if (file.isDirectory()) {
                listDirectories(file.getAbsolutePath());
            }
         }
    } // method listDirectories

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote