Listing 13: FindFile.java — Searches a subdirectory tree for an entry

import java.io.*;

class FindFile
{
    public static void main(String[] args)
    {
        String dir = null;
        if (args.length < 2)
            dir = new String(".");
        else
            dir = args[1];
        try
        {
            search(new File(dir), args[0]);
        }
        catch (IOException e)
        {
            System.out.println(e.getMessage());
        }
    }
    
    static void search(File dir, String name)
        throws IOException
    {
        File[] files = dir.listFiles();
        if (files == null)
            throw new IOException("not a valid directory");
        for (int i = 0; i < files.length; ++i)
        {
            if (files[i].getName().compareToIgnoreCase(name) == 0)
            {
                System.out.println(files[i].getCanonicalPath());
            }
            if (files[i].isDirectory())
                search(files[i], name);
        }
    }
}

/* Output of 'java FindFile foo':
C:\CUJ\temp\foo
*/
— End of Listing —