Calculating Folder Size Graphically and Generating Directory Size Chart In Java

Why I Wrote this Program?
I had a large collection of my personal pictures and videos on many folders on my laptop. I wanted to know which folder is taking lots of spaces. In fact I wanted to compare the total sizes taken by those folders.

What this program does?
This program recurses through a folder, finds the total size occupied by the folder. For my own use, I modified it to go level down and find the sizes of individual folders at that level.

This class generates a graphical chart of total folder sizes of any given folder’s one level down subfolders.

For instance, if you have a Folder A which has B,C,D as immediate subfolders (which in turn may have many other subfolders).This class will take folder A as an input and create a graph of folder sizes of folders at level B, C, D.

Total size at level B, C and D is calculated by recursively going to all subfolders. See the diagram below.

Then using JFreeChart API, it draws simple Bar Chart (3D) to show the total folder sizes at that level.

Requirements:
— JFreeChart API (available at JFree.org)

package com.kushal.charts;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 2009-10-07
 *
 * This class generates a graphical chart of total folder sizes
 * of any given folder's one level down subfolders.
 *
 * For instance, if you have a Folder A which has B,C,D as immediate
 * subfolders (which in turn may have many other subfolders).This class
 * will take folder A as an input and create a graph of folder sizes
 * of folders at level B, C, D.
 *
 * Total size at level B, C and D is calculated by recursively going to
 * all subfolders.
 */
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

public class FolderGraph {

static int totalFolderCount = 0;

static 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:\Program Files\DbVisualizer-6.5.4";

ArrayList dataList = new ArrayList();

File myFile = new File(folder);
File[] fileArray = myFile.listFiles();

for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isDirectory()) {
long fileSizeByte = getFileSize(new File(fileArray[i]
.getAbsolutePath()));
MyFileObj obj = new MyFileObj(fileArray[i].getName(),
fileSizeByte / (1024 * 1024));
dataList.add(obj);

}
}

CategoryDataset categoryDataset = createCategoryDataset(dataList);
JFreeChart chartHorizontal = create3DBarChart(categoryDataset,
PlotOrientation.VERTICAL);

/** Define a location to save this created file* */
String horizontalChartFileSaveLocation = "C:/temp/myFolderSizeGraph.jpg";

/** Save the chart to the file system* */
saveChart(chartHorizontal, horizontalChartFileSaveLocation);

System.out.println("done");

}

/**
* This is a recursive method. If file is found, total file size is
* calculated. If it is a folder, we recurse further.
*/
public static 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;
}

private static CategoryDataset createCategoryDataset(ArrayList myFileObjArr) {
final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

for (int i = 0; i < myFileObjArr.size(); i++) {
dataset.addValue(((MyFileObj) myFileObjArr.get(i))
.getFolderSizeTotal(), "Folder Size (MB)",
((MyFileObj) myFileObjArr.get(i)).getFolderName());
}
return dataset;

}

private static JFreeChart create3DBarChart(CategoryDataset dataset,
PlotOrientation plotOrientation) {
JFreeChart chart = ChartFactory.createBarChart3D(
"FolderGraph - www.sanjaal.com/java", // Chart Title
"Folder Name", // Domain Axis Label
"Folder Size", // Range Axis Label
dataset, // Data
plotOrientation, // Orientation
true, // Include Legend
true, // Tooltips
false // Urls
);

return chart;

}

public static void saveChart(JFreeChart chart, String fileLocation) {
try {
/**
* This utility saves the JFreeChart as a JPEG First Parameter:
* FileName Second Parameter: Chart To Save Third Parameter: Height
* Of Picture Fourth Parameter: Width Of Picture
*/
ChartUtilities.saveChartAsJPEG(new File(fileLocation), chart, 900,
900);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Problem occurred creating chart.");
}
}

}

class MyFileObj {
String folderName;

long folderSizeTotal;

public MyFileObj(String folderName, long folderSizeTotal) {
this.folderName = folderName;
this.folderSizeTotal = folderSizeTotal;

}

/**
* @return the folderName
*/
public String getFolderName() {
return folderName;
}

/**
* @param folderName
*            the folderName to set
*/
public void setFolderName(String folderName) {
this.folderName = folderName;
}

/**
* @return the folderSizeTotal
*/
public long getFolderSizeTotal() {
return folderSizeTotal;
}

/**
* @param folderSizeTotal
*            the folderSizeTotal to set
*/
public void setFolderSizeTotal(long folderSizeTotal) {
this.folderSizeTotal = folderSizeTotal;
}

/*
* SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
* SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
* MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
* HIGH RISK ACTIVITIES.
*/
}


Sample output of running this program on my system:

Processing .install4j
Processing doc
Processing images
Processing licenses
Processing jdbc
Processing db2
Processing derby
Processing jtds
Processing mimer
Processing mysql
Processing postgresql
Processing jre
Processing bin
Processing client
Processing new_plugin
Processing lib
Processing applet
Processing cmm
Processing deploy
Processing jqs
Processing ff
Processing chrome
Processing content
Processing ie
Processing ext
Processing fonts
Processing i386
Processing im
Processing images
Processing cursors
Processing management
Processing security
Processing servicetag
Processing zi
Processing Africa
Processing America
Processing Argentina
Processing Indiana
Processing Kentucky
Processing North_Dakota
Processing Antarctica
Processing Asia
Processing Atlantic
Processing Australia
Processing Etc
Processing Europe
Processing Indian
Processing Pacific
Processing SystemV
Processing lib
Processing resources
Processing keymaps
Processing profiles
Processing resources
Processing wrapper
Processing classes
Processing com
Processing onseven
Processing dbvis
Processing wrapper
done

The generated graph:

  1. How to read / write UTF8 and Non-UTF8 files in Java
  2. Creating Time Series Chart With JFree Chart
  3. Creating A 3D Category Bar Chart In Java Using JFreeChart [Example Source Code]
  4. How To Print A Text File In Java
  5. How to read a tab separated or tab delimited file in Java program and print the content to console
  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. File Copy From Local Folder or Network Folder Using Java With Capability To Limit The Number
  9. Java Object Serialization and Deserialization In MySQL Database
  10. How To Set Conditional Debug Breakpoints in Eclipse or IBM RAD?
  11. Rotating An Image In Java Graphics 2D By Specified Degree
  12. Java Tutorial – Using JCIFS to copy files to shared network drive using username and password
  13. Java – How To Overlay One Image Over Another Using Graphics2D [Tutorial]
  14. Creating 3D Pie Chart using JFreeChart with chart data read from file
  15. Creating Gantt Chart In Java Using JFreeChart API [Example/Tutorial]
  16. Quick SQL Reference – Find Duplicate Data In A Table Using Having Clause
  17. Splitting PDF File Using Java iText API Into Multiple PDFs
  18. Reading / Writing File in Java and String Manipulation
  19. Object Serialization And De-Serialization In Java To Filesystem
  20. Finding Java Image Pixels Information – ARGB (Alpha, Red, Green Blue)
  21. Creating A 3D Pie Chart In Java Using JFreeChart [Example Source Code]
  22. Java Tutorial – Swing Text Drag And Drop – Sample Example
  23. Serialzing A Java Object Into XML and De-Serialzing using XMLEncoder And XMLDecoder
  24. Six Stages Of Debugging in Software Engineering
  25. Java 2D Graphics Example Tutorial On Paint, Gradient and Stroke
  26. How To Read DOC file Using Java and Apache POI
  27. Complete Tutorial On Using SOAP-UI to Mock Web Service Request / Response
  28. Writing To Excel File Using Apache POI
  29. Listing The Content Of Zip File With Zip Information In Java
  30. Joke – Why do Java Programmers wear glasses?
  31. How to receive files via bluetooth in your MacBook Pro
  32. Creating Category Chart Using JFreeChart
  33. Reading Excel File Using Java And Apache POI
  34. Calculating Folder Size In Java
  35. How To Rename A File In Java
  36. 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 *