Javatpoint Logo
Javatpoint Logo

Java Program to Get the Size of a Directory

The Java program used to get the size of a directory can calculate the total size of a directory and all the files and folders inside it using a recursive approach. By using this program, one can obtain valuable insights into the size of a directory.

Algorithm

  1. Declare a private static method getDirectorySize that recursively calculates the size of a directory by iterating through all its contents, both files and directories.
  2. Inside getDirectorySize, use the listFiles method of the File class to obtain an array of all the files and directories inside the given directory.
  3. Loop through each file and directory in the array and add the file size to a running total if it's a file, or recursively call getDirectorySize if it's a directory.
  4. In the main method, create a File object for the directory whose size you want to calculate and call getDirectorySize to get the size in bytes.
  5. Convert the size to kilobytes and megabytes and print the results, along with the number of files and directories in the directory and its last modified time.

Implementation

Filename: DirectoryFile.java

Output:

Size of directory C:\Users\maddu\OneDrive\Desktop\Watcher:
  251475 bytes
  245.5810546875 KB
  0.23982524871826172 MB
Number of files: 10
Number of directories: 0
Last modified: 1682263462278






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA