import java.io.*; import java.util.*; public class FileWalk implements Runnable { protected File base; protected int indent; protected PrintStream out; /** * Create a FileWalk object for the given string, with * a print indentation given. */ public FileWalk(String filename, int i) { base = new File(filename); indent = i; out = System.out; } static class Stats { public int totalCount; public long totalSize; public Stats() { totalCount = 0; totalSize = 0; } public void add(File f) { totalCount++; if (!f.isDirectory()) { totalSize += f.length(); } } public void add(Stats s) { totalCount += s.totalCount; totalSize += s.totalSize; } public String toString() { return "Files: " + totalCount + ", total size: " + totalSize; } } public void setOutput(PrintStream ps) { out = ps; } public void run() { Stats stats = new Stats(); process(base, 0, indent, out, stats); if (stats.totalCount > 1) out.println("Grand total: " + stats); } static String dup(char c, int i) { StringBuffer bt = new StringBuffer(i); while(i > 0) { bt.append(c); i--; } return bt.toString(); } static void process(File b, int ind, int incr, PrintStream ps, Stats s) { try { if (b.isDirectory()) { s.add(b); ps.print(dup(' ',ind)); ps.print("Directory " + b.getCanonicalPath()); ps.print(" ["); ps.print((b.canRead())?("readable,"):("not readable,")); ps.print((b.canWrite())?("writable"):("not writable")); ps.print("]\n"); Stats mys = new Stats(); String [] subs = b.list(); if (subs.length > 0) { // if you don't have Java 2 platform, comment out this line Arrays.sort(subs); // for(int i = 0; i < subs.length; i++) { File f2 = new File(subs[i]); if (f2.equals(b)) continue; if (f2.equals(b.getParentFile())) continue; // recurse here! process(new File(b,subs[i]), ind + incr, incr, ps, mys); } ps.print(dup(' ',ind)); ps.println(b.getCanonicalPath() + " " + mys); } else { ps.print(dup(' ',ind)); ps.println(b.getCanonicalPath() + " - empty directory"); } } else { s.add(b); ps.print(dup(' ',ind)); ps.print(b.getName()); ps.print(" size: " + b.length() + " bytes ["); ps.print((b.canRead())?("readable,"):("not readable,")); ps.print((b.canWrite())?("writable"):("not writable")); ps.print("]\n"); } } catch (IOException ie) { ps.println("Exception on path: " + ie); } } public static void main(String [] args) { String basename = "."; if (args.length > 0) { basename = args[0]; } System.out.println("Base name is: " + basename); FileWalk walker = new FileWalk(basename, 4); walker.setOutput(System.out); walker.run(); } }