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

Write a method void listAllFiles (File dir) that recursively displays a list of

ID: 3819263 • 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

Java Code :


import java.io.*;
import java.lang.*;

public class ListFilesUtil {
  
public void listFiles(String directoryName){
File directory = new File(directoryName);
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
System.out.println(file.getName());
}
}
}
  
public void listAllFiles(String directoryName){
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
  

System.out.println(file.getName());
} else if (file.isDirectory()){
String parts = file.getAbsolutePath();
String parts1 = parts.replace("\","-");
String part1[]=parts.split("-");
System.out.println(part1[part1.length-1]);
listAllFiles(file.getAbsolutePath());
}
}
}
public static void main (String[] args){
ListFilesUtil listFilesUtil = new ListFilesUtil();
  
final String directoryWindows ="G:\My Personal";
listFilesUtil.listAllFiles(directoryWindows);
  
}
}

Output :

run:
G:My PersonalAnnie
hr.txt
Anupam-Sakhi Resume (2)-1.doc
lic.pdf
G:My PersonalRishi
G:My PersonalRishiHrishi
hri.txt
BUILD SUCCESSFUL (total time: 0 seconds)

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