Write a method void listAllFiles(File dir) that recursively displays a list of a
ID: 3826285 • Letter: W
Question
Write a method void listAllFiles(File dir) that recursively displays a list of a directory's files and subdirectories. An example is illustrated below. Note the following in the output:
Directory names are all capitalized and written between brackets [ ].
Files and subdirectories are indented in order to illustrate to which parent directory they belong. Use a helper method void listAllFiles(File dir, String spaces) where dir represents the root directory (i.e., Folder 1 in the example below) and spaces stores a number of spaces " " that is incremented every time the method is recursively called. The helper method should print out spaces followed by the file or subdirectory names.
Explanation / Answer
package com;
import java.io.File;
import java.io.IOException;
public class List {
public static void main(String[] a)throws IOException{
listAllFiles(1, new File("C:/Users/miracle/Desktop/c1"));
}
static void listAllFiles(int indent, File file) throws IOException {
for (int i = 0; i < indent;i++) System.out.print(' ');
System.out.println(file.getName());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)listAllFiles(indent + 2 , files[i]);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.