Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Using listAllFiles as a guide, write a method that has one File argument: if the argument is a directory, the method returns the total number
Using listAllFiles as a guide, write a method that has one File argument: if the argument is a directory, the method returns the total number of files below it. If the argument represents a file, the method just returns 1. public static int countFiles(File f)
import java.io.File; public class FileLister { public static void main(String[] args) { // Choose the directory you want to list. // If running in Eclipse, "." will just be the current project directory. // Use ".." to list the whole workspace directory, or enter a path to // some other directory. File rootDirectory = new File("."); listAllFiles(rootDirectory); } /** * Print the names of all items in the hierarchy located under * a given directory. If the given File object is not a directory, * just prints the file's name. */ public static void listAllFiles(File f) { if (!f.isDirectory()) { // Base case: f is a file, so just print its name System.out.println(f.getName()); } else { // Recursive case: f is a directory, so go through the // files and directories it contains, and recursively call // this method on each one System.out.println("+ " + f.getName()); File[] files = f.listFiles(); for (int i = 0; i < files.length; ++i) { listAllFiles(files[i]); } } } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started