Title: Recursion and the File class
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Recursion and the File class

In this video, we will drill down through a file system directory structure and count the total number of files, and number of bytes. The key methods in the File class used are:

- list()
- isDirectory()
- length()

Recursion is a powerful technique and walking through a file system directory is a perfect fit for recursion:

Program created in the video: FileStats.java

import java.io.File;

class Stats
{
    long numFiles = 0;
    long numBytes = 0;
    long numDirs = 0;

    public String toString()
    {
        return "numFiles =" + numFiles + " numBytes="+numBytes + " numDirs="+numDirs;
    }
}

public class FileStats {
    boolean verbose = false;

    FileStats(boolean verbose)
    {
        this.verbose = verbose;
    }
    public Stats collectData(String pathname)
    {
        Stats stats = new Stats();
        File file = new File(pathname);
        System.out.println(" pathname="+ pathname);
        System.out.println("Full pathname=" + file.getAbsolutePath());
        recursiveCollect(file, pathname, stats);
        System.out.println(" stats = " + stats);
        return stats;
    }

    public void recursiveCollect(File f, String pathname, Stats stats)
    {
        if (verbose)
            System.out.println(pathname);

        stats.numFiles +=1;
        if (f.isDirectory())
        {
            stats.numDirs += 1;
            String[] fileNames = f.list();
            if (fileNames != null)
            {
                for (int i=0; i < fileNames.length; i++)
                {
                    String newPathname = pathname + File.separator + fileNames[i];
                    File f2 = new File(newPathname);
                    recursiveCollect(f2, newPathname, stats);
                }
            }
        }
        else
            stats.numBytes += f.length();
    }

    public static void main(String[] args) {
        FileStats fs = new FileStats(true);

        if (args.length > 0)
            fs.collectData(args[0]);
        else
            fs.collectData(".");

    }

}



Last Updated: July 28, 2014 10:42 AM