Q:

(Directory size) Listing 20.7, DirectorySize.java, gives a recursive method for finding a directory size

0

(Directory size) Listing 20.7, DirectorySize.java, gives a recursive method for finding a directory size. Rewrite this method without using recursion. Your program should use a queue to store the subdirectories under a directory. The algorithm can be described as follows:

long getSize(File directory) {
long size = 0;
 add directory to the queue;
while (queue is not empty) {
 Remove an item from the queue into t;
if (t is a file)
 size += t.length();
else
 add all the files and subdirectories under t into the 
 queue;
 }
return size;
}

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

/*********************************************************************************
* (Directory size) Listing 20.7, DirectorySize.java, gives a recursive method    *
* for finding a directory size. Rewrite this method without using recursion.     *
* Your program should use a queue to store the subdirectories under a directory. *
*********************************************************************************/
import java.io.File;
import java.util.*;

public class Exercise_20_18 {
	public static void main(String[] args) {
		// Prompt the user to enter a directory or a file
		System.out.print("Enter a directory or a file: ");
		Scanner input = new Scanner(System.in);
		String directory = input.nextLine();

		// Display the size
		System.out.println(getSize(new File(directory)) + " bytes");
	}

	/** Returns the size of a directory */
	public static long getSize(File file) {
		// Create a Queue
		Queue<File> queue = new LinkedList<>();
		long size = 0; // Accumulates the directory size
		
		addDirectory(queue, file);

		while (!queue.isEmpty()) {
			// Remove an item form the queue into t
			File t = queue.remove();
			if (t.isFile())
				size += t.length();
			else // Add all files and subdirectories under t into the queue
				addDirectory(queue, t);
		}

		return size;
	}

	/** Adds a Directory to the queue */
	private static void addDirectory(
			Queue<File> queue, File directory) {
		for (File file: directory.listFiles()) {
			queue.offer(file);
		};
	}
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now