Question: This is a graded exercise which should be posted to your learning journal. The sample program DirectoryList.java (in the code directory), given as an example
This is a graded exercise which should be posted to your learning journal. The sample program DirectoryList.java (in the code directory), given as an example in section 11.2.2 of the textbook will print a list of files in a directory specified by the user. But some of the files in that directory might themselves be directories. And the subdirectories can themselves contain directories. And so on. Write a modified version of DirectoryList that will list all the files in a directory and all its subdirectories, to any level of nesting. You will need a recursive subroutine to do the listing. The subroutine should have a parameter of type File. You will need the constructor from the File class that has the form
public File( File dir, String fileName ) // Constructs the File object representing a file // named fileName in the directory specified by dir.
SAMPLE PROGRAM
import java.io.File;
import java.util.Scanner;
/**
* This program lists the files in a directory specified by
* the user. The user is asked to type in a directory name.
* If the name entered by the user is not a directory, a
* message is printed and the program ends.
*/
public class DirectoryList {
public static void main(String[] args) {
String directoryName; // Directory name entered by the user.
File directory; // File object referring to the directory.
String[] files; // Array of file names in the directory.
Scanner scanner; // For reading a line of input from the user.
scanner = new Scanner(System.in); // scanner reads from standard input.
System.out.print("Enter a directory name: ");
directoryName = scanner.nextLine().trim();
directory = new File(directoryName);
if (directory.isDirectory() == false) {
if (directory.exists() == false)
System.out.println("There is no such directory!");
else
System.out.println("That file is not a directory.");
}
else {
files = directory.list();
System.out.println("Files in directory \"" + directory + "\":");
for (int i = 0; i < files.length; i++)
System.out.println(" " + files[i]);
}
} // end main()
} // end class DirectoryList
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
