Problem Description:
Write a program that prompts the user to enter a directory and displays the number of the files in the directory.
Analysis:
(Describe the problem including input and output in your own words.)
Design:
(Describe the major steps for solving the problem. How do you use recursion to solve this problem.)
Coding: (Copy and Paste Source Code here. Format your code using Courier 10pts)
Name the public class Exercise18_29
Testing: (Describe how you test this program)
Problem: To get count of files present inside a given directory path (including any of its sub-directories). Input to the program should be a valid directory absolute path. For every valid input, the program outputs the total count of files present inside the input directory path including any of its sub-directories). The count excludes directory count, if any.
Design: Below are the major steps in solving this problem using Java:
Recursion is used under point 4 since we also want to include files inside sub-directories in the total count. A "for" loop iterates through the list of files/directories inside "getFilesCount" function. During iteration, if another directory is found, the function "getFilesCount" get called recursively and the whole thing repeats for list of files/directories found in the sub-directory.
Code:
import java.io.File;
import java.util.Scanner;
public class Exercise18_29 {
public static void main(String[] args) {
//Ask user to enter
directory
System.out.print("Specify a directory path:");
//Read the user input
Scanner input = new
Scanner(System.in);
String path =
input.nextLine();
File dir = new File(path);
//Check if input path is of a
directory (also is assumed valid)
if(dir.isDirectory())
System.out.println(getFilesCount(new File(path)) + " files");
else
System.out.println("Specified path is not a valid directory
path.");
}
public static int getFilesCount(File file) {
//Initialize a file object array
for file/directory list
File[] files =
file.listFiles();
//Count variable that will be
returned finally to the caller
int count = 0;
//For loop to iterate through list
of files/directories
for (File f : files)
if
(f.isDirectory())
//Recursive function call
count += getFilesCount(f);
else
count++;
//Return the count to the
caller
return count;
}
}
Testing: For testing this code, below process is followed:
Problem Description: Write a program that prompts the user to enter a directory and displays the...