Calculating Folder Size In Java

The following piece of java code demonstrates how we can calculate the size of a given folder using Java Application. This uses a recursive technique. We start with a root directory, and start listing the files/folder. If a file is found, we calculate its size and sum of total size and also increase the total number of files counted so far, if it is a directory, we further do the recursion.

This program has been fully compiled and tested to find the folder size in Java.

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 30th August 2008
 */
package com.kushal.utilities;

import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class TopLevelFolderSize {

	int totalFolderCount=0;
	int totalFileCount=0;

	public static void main(String args [])
	{
		/**
		 * Define your folder here. This is the folder whose size
		 * statistics you want to find out.
		 */
		String folder = "C:/Users/kushal/Desktop/tempKushal";

		try{
			DecimalFormat fmt =new DecimalFormat("#.##");

			TopLevelFolderSize fg=new TopLevelFolderSize();

			/**Calculating the file size. By default size in long
			 * is returned.
			 */
			long fileSizeByte=fg.getFileSize(new File(folder));

			/**
			 * Formatting the long value to calculate size in
			 * different units KB, MB and GB
			 */
			double fileSizeKB=Double.valueOf(fmt.format(fileSizeByte /1024));
			double fileSizeMB=Double.valueOf(fmt.format(fileSizeByte /(1024*1024)));
			double fileSizeGB=Double.valueOf(fmt.format(fileSizeByte /(1024*1024*1024)));

			/**Printing the statistics**/
			System.out.println("nn##############--Folder Statistics--#################");
			System.out.println("Total Folder Size: ["+fileSizeByte+" Bytes] ntt["
						+fileSizeKB+" KB] ntt["
						+fileSizeMB+" MB] ntt["
						+fileSizeGB+" GB]");
			System.out.println("Total Number of Folders: "+fg.getTotalFolderCount());
			System.out.println("Total Number of Files: "+fg.getTotalFileCount());
			System.out.println("##########--End Of Folder Statistics--##############");

		}catch (Exception e)
		{
			System.out.println("Exception Occurred: "+e.getMessage());
		}
	}

	/**
	 * This is a recursive method.
	 * If file is found, total file size is calculated.
	 * If it is a folder, we recurse further.
	 */
	public long getFileSize(File folder) {
		totalFolderCount++; //Counting the total folders

		System.out.println("Processing " + folder.getName());
		long foldersize = 0;

		File[] filelist = folder.listFiles();
		for (int i = 0; i < filelist.length; i++) {
			if (filelist[i].isDirectory()) {
				foldersize += getFileSize(filelist[i]);
			} else {
				totalFileCount++; //Counting the total files
				foldersize += filelist[i].length();
			}
		}

		return foldersize;
	}

	/**
	 * @return the totalFolderCount
	 */
	public int getTotalFolderCount() {
		return totalFolderCount;
	}

	/**
	 * @return the totalFileCount
	 */
	public int getTotalFileCount() {
		return totalFileCount;
	}

}


———————————————————————
SAMPLE OUTPUT:
———————————————————————
Processing tempKushal
Processing cute pictures
Processing image col
Processing Moline Tornado
Processing send
Processing Party At Prabhakars
Processing images

##############–Folder Statistics–#################
Total Folder Size: [151850658 Bytes]
[148291.0 KB]
[144.0 MB]
[0.0 GB]
Total Number of Folders: 7
Total Number of Files: 154
##########–End Of Folder Statistics–##############

  1. How to extract plain Text from HTML Website easily in Java
  2. How to read / write UTF8 and Non-UTF8 files in Java
  3. How To Print A Text File In Java
  4. How to read a tab separated or tab delimited file in Java program and print the content to console
  5. How To Find What Java Version You Are Using?
  6. Computing the total, free and usable disk space easily using JDK 1.6
  7. Reading the Resource or Property files in Java as a file stream and outputting the content to console
  8. Creating java.util.date and java.util.sql objects from Calendar object
  9. File Copy From Local Folder or Network Folder Using Java With Capability To Limit The Number
  10. Bar Code Generation In Java Using iText API
  11. Simple Tag Generator In Java For Music Blogs
  12. Tutorial on Converting an List of Strings or Numbers to a CSV file with optional sorting
  13. Calling URL Browser From Java Application
  14. Java Reflection Tutorial – List Methods Of A Class
  15. Cleaning Punctuation And White Spaces From A String
  16. Java Tutorial – Using JCIFS to copy files to shared network drive using username and password
  17. Prime Number Finder In Java
  18. Utility Class For Getting SQL Connection and Closing It
  19. Java Design Pattern – Singleton Pattern
  20. Reading / Writing File in Java and String Manipulation
  21. How to capture a screenshot using Java and save it to a file?
  22. Calculating The Difference Between Two Dates In Terms of Months
  23. Getting The Name Of Currently Logged In User In The System
  24. How To Set And Get System Clipboard Contents In Java
  25. RGB To Hex and Hex To RGB Conversion Using Java and Regular Expressions
  26. Generating Nepali Unicode Sequence For Characters
  27. How To Read DOC file Using Java and Apache POI
  28. Writing To Excel File Using Apache POI
  29. Java Tool To Compare Two Lists and Spit Out The Differences – Working Example
  30. Replacing non-ASCII characters using Java Regular Expressions
  31. Reading Excel File Using Java And Apache POI
  32. Calculating Folder Size In Java
  33. How To Rename A File In Java
  34. Calculating Folder Size Graphically and Generating Directory Size Chart In Java
Tagged , , , , , , , . Bookmark the permalink.

One Response to Calculating Folder Size Graphically and Generating Directory Size Chart In Java

  1. nocdib says:

    Thank you for this! It is just what I need

Leave a Reply

Your email address will not be published. Required fields are marked *