(Nonrecursive directory size) Rewrite Listing 1, DirectorySize.java, without using recursion.
LISTING 1 DirectorySize.java
1 import java.io.File;
2 import java.util.Scanner;
3
4 public class DirectorySize {
5 public static void main(String[] args) {
6 // Prompt the user to enter a directory or a file
7 System.out.print("Enter a directory or a file: ");
8 Scanner input = new Scanner(System.in);
9 String directory = input.nextLine();
10
11 // Display the size
12 System.out.println(getSize(new File(directory)) + " bytes");
13 }
14
15 public static long getSize(File file) {
16 long size = 0; // Store the total size of all files
17
18 if (file.isDirectory()) {
19 File[] files = file.listFiles(); // All files and subdirectories
20 for (int i = 0; files != null && i
21 size += getSize(files[i]); // Recursive call
22 }
23 }
24 else { // Base case
25 size += file.length();
26 }
27
28 return size;
29 }
30 }
![]()
![]()
![]()
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.