How to find Directory size in Java

In this post I am going to find size of any directory using recursion in java. 

What is Recursion?

Recursion means a method; calling directly or indirectly themselves. Recursion is a useful programming technique. In some cases, it enables you to develop a straightforward and simple solution to an otherwise difficult problem. This post introduces you how  find size of directory using recursion in java. 
 
The size of a directory is the sum of the sizes of all files in the directory. A directory d may contain subdirectories. Suppose a directory contains files f1, f2, f3, ...., fn. and subdirectories d1, d2,...., dn, as shown in below formula:

size(d) = size(f1) + size(f2)+ ... + size(fm) + size(d1) + size(d2) + ... + size(dn)

This sample code listing prompts the user to enter a directory or a file and displays its size. 


DirectorySize.java




import java.io.File;
import java.util.Scanner;

public class DirectorySize {
       public static void main(String[] args) {
              // Prompt the user to enter a directory or a file
              System.out.print("Please 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");
       }

       public static long getSize(File file) {
               long size = 0; // Store the total size of all files
      
               if (file.isDirectory()) {
                      File[] files = file.listFiles(); // All files and subdirectories
                      for (int i = 0; i < files.length; i++) {
                             size += getSize(files[i]); // Recursive call
                   }
               }
               else { // Base case
                      size += file.length();
               }
             
               return size;
       }
}
   Output of the above code listing would look like:

   Please Enter a Directory or a File: F:\J2EE Tutorials
  6186525764 bytes


No comments:

Post a Comment