/*****************************************************************
** JavaFind - mimic the basic operation of the DOS FIND command
**
** (c) Scott MacKenzie, 2000                             
******************************************************************/
import java.io.*;

public class JavaFind
{
   public static void main(String[] args) throws IOException
   {
      if (args.length < 2)
      {
         System.out.println(
            "Find a string in one or more files in current directory\n\n" +
            "Usage: java JavaFind string file\n\n" +
            "where 'string' is a string to find\n" +
            "      'file' is the file(s) to search\n\n" +
            "Example: java JavaFind print( *.java\n\n" +
            "  finds lines containing 'print(' in all files\n" +
            "  with names ending in '.java'");
         return;
      }

      // get a list of all files in current directory
      File f = new File(".");
      String[] s = f.list();

      String line;
      BufferedReader inputFile;

      for (int i = 0; i < s.length; i++)
      {
         // see if filename matches command-line arg file
         if (match(s[i], args))
         {  
            // open disk file for input
            inputFile = new BufferedReader(new FileReader(s[i]));

            int n = 0;
            boolean firstTime = false;
            while ((line = inputFile.readLine()) != null)
            {
               if (line.indexOf(args[0]) != -1)
               {
                  if (firstTime == false)
                  {
                     System.out.println("\n----- " + s[i] + " -----");
                     firstTime = true;
                  }
                  System.out.println(n + ": " + line);
               }
               n++;
            }
            inputFile.close();
         }
      }
   }

   public static boolean match(String f1, String[] f2)
   {
      if (f2.length == 0)
         return true;
      for (int i = 0; i < f2.length; i++)
         if (f1.equals(f2[i]))
            return true;
      return false;
   }
}

