/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * DirectoryDiskUsage.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 3-4: * Write a program that adds up and reports the size of all files in a * specified directory. It should recursively scan any subdirectories, * summing and reporting the size of the files that they contain, and * incorporate those directory sizes into its final output. * * @author Matthew Feldt * @version 1.0, 01/30/2001 10:56 */ package com.feldt.examples.io; import java.io.*; class DirectoryDiskUsage { /** * Static method to recursively compute the amount of storage used * in a specified directory. */ public static long getDiskUsage(File dir) throws IllegalArgumentException { long total = 0; if (! dir.exists()) throw new IllegalArgumentException(dir + " does not exist."); if (! dir.canRead()) throw new IllegalArgumentException(dir + " read protected."); File[] entries = dir.listFiles(); for (int i = 0; i < entries.length; i++) { if (entries[i].isFile()) total += entries[i].length(); else if (entries[i].isDirectory()) // recurse total += getDiskUsage(entries[i]); } return total; } /** test class */ static class Test { public static void main (String args[]) { final String usage = "Usage: java DirectoryDiskUsage$Test dir"; if (args.length != 1) { System.err.println(usage); System.exit(-1); } File dir = new File(args[0]); System.out.println(dir + " " + DirectoryDiskUsage.getDiskUsage(dir)); } } }