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
- Declare a private static method getDirectorySize that recursively calculates the size of a directory by iterating through all its contents, both files and directories.
- Inside getDirectorySize, use the listFiles method of the File class to obtain an array of all the files and directories inside the given directory.
- 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.
- 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.
- 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
|