


//////////////////////////////////////////////////
//
// ReplaceinFile1.java   Version 1.01
// Replaces a given character string with a new string for all files
// (matching the identified file extension) in the default directory.
//
// (I'll be adding a snazzy user interface soon
//
//
// (and yes, I know it's sorta kludgy, but it works and I needed it
//  for a work-related situation. Suggestions, improvements, comments are 
//  welcomed at 102107.1004@compuserve.com)
//
// Copyright (c) 1996 Kenny A. Chaffin. All Rights Reserved
//
// Usage: java ReplaceinFile1 <search string> <replacement string> 
//                 <-e extension> <-d> <-bd beginningdirectory(full path)>
//
//   -d means process subdirectories, the extension should not include a "."
//   the beginning directory should be the _full_ path, including drive letter.
//   search and replacement strings can include spaces, if the string is quoted
//
//   Example: java ReplaceinFile1 body JUNK -e html -d -bd c:\testdir
//   Example2: java ReplaceinFile1 "A Test" JUNK -e txt
//
//
// Created 4/2/96 by Kenny A. Chaffin
// Last updated 4/14/96 by Kenny A. Chaffin 
//   Fixed to properly handle directory paths
//   added beginning directory option (default is current directory)
//
// Note: This is not commercial software and the author makes no warranties
// about the suitability of this software for any system. The author shall 
// not be liable for any damages suffered as a result of anyone using, modifying,
// or distributing this software or its derivatives.
//
// feel free to copy, modify, and distribute this program provided you leave the 
// above information.
//////////////////////////////////////////////////



import java.io.*;

  
class EndsWithFilter implements FilenameFilter
  {
    private String extension;
    public EndsWithFilter(String extension)
      {
        this.extension = extension;
      }
    public boolean accept(File dir, String name)
      {
        if (name.endsWith(extension)) return true;
        else return (new File(dir, name)).isDirectory();
      }
  }

class procdir
    {
       
  public String[] list_directory(String directory,  FilenameFilter filter) throws IOException
      {
        File cwd;      
        String[] entries;

        File dir = new File(directory);
        
        if (!dir.isDirectory())
          throw new IllegalArgumentException("list_directory: no such directory");
        cwd = dir;
        
        entries = cwd.list(filter);
        return entries;       
      }

    
  public static String Replace(String line, String findString, String repString)
    {				//Replace a string in the supplied line
        StringBuffer newstring;
        int position;
        
        newstring = new StringBuffer();

        if ((position = line.indexOf(findString)) != -1)
           { 
             newstring.append(line.substring(0, position));
             newstring.append(repString);
             position = position + findString.length();
             newstring.append(line.substring(position, line.length()));
             return newstring.toString();
           }
         else
           {
             newstring.append(line);
             return newstring.toString();
           }
      }

     public procdir(String dir, String ext, String sstring, String rstring, boolean dosubdirs) throws IOException
      {
        FilenameFilter filter = null;
        String directory = null;
        FileInputStream in = null;
        FileOutputStream out = null;
        String line;
        StringBuffer newfilename;
        StringBuffer backupname;
	int position;
	File testfile = null;
	File backupfile = null;
	File outfile = null;
	File tempfile = null;
	File WorkingDirectory = null;
	procdir p;
	String[] entries;
	
	
    filter = new EndsWithFilter(ext);
    entries = list_directory(dir, filter);
    WorkingDirectory = new File(dir);
        
// we've got the file list in entries[]
// process them here
        
    for (int i=0; i < entries.length; i++)   //for testing
      System.out.println(entries[i]);
 
    for (int i=0; i < entries.length; i++)
     { 
       try
         {testfile = new File(WorkingDirectory, entries[i]);}   //set up new file name
       catch(Throwable e)
         { 
           System.out.println("Error opening file: " + entries[i]);
           System.exit(1);
         }
  
       if (testfile.isFile())
        {    
           in = new FileInputStream(testfile);
           newfilename = new StringBuffer();
           backupname = new StringBuffer();		//for renaming

           if ((position = entries[i].indexOf('.')) != -1)
              { 
                newfilename.append(entries[i].substring(0, position));
                newfilename.append(".out");
                backupname.append(entries[i].substring(0, position));
                backupname.append(".old");
                
              }
           System.out.println(newfilename.toString());
           out = new FileOutputStream(new File(WorkingDirectory, newfilename.toString()));
           backupfile = new File(WorkingDirectory, backupname.toString());
           outfile = new File(WorkingDirectory, newfilename.toString());
      
       DataInputStream datainfile = new DataInputStream(in);
       DataOutputStream dataoutfile = new DataOutputStream(out);
       try
         {
           while ((line = datainfile.readLine()) != null)
             {			//  process lines here            
                dataoutfile.writeBytes(Replace(line, sstring, rstring) + "\r\n");
//                System.out.println(Replace(line, sstring, rstring));
             }
           
           in.close();
           out.close();
           if (backupfile.exists())        // if there's an old one get rid of it 
             backupfile.delete();
           tempfile = testfile;
           testfile.renameTo(backupfile);
           outfile.renameTo(tempfile);           
         }
       catch(IOException e)
         {
           System.out.println("I/O Error");
           System.exit(1);
         }
      }
     else
       {
         if (dosubdirs)
           {
             System.out.println("Processing directory: " + WorkingDirectory + "\\" + entries[i]);
             p = new procdir(WorkingDirectory + "\\" + entries[i], ext, sstring, rstring, dosubdirs);
           };
       }
    }
  }
}
  
public class ReplaceinFile1
  {

    public static void usage()
      {
        System.out.println("Usage: java ReplaceinFile <search string> <replacement string> <-e extension> <-d> <-bd beginningdirectory>");
        System.exit(0);
      }
      
    public static void main(String args[]) throws IOException
      {
        String directory = null;
        String extension = null;
        boolean dodirs = false;
        procdir p;
        
         if (args.length <= 2) usage();
      
         for (int i=0; i< args.length; i++)
           {
             if (args[i].equals("-e"))
               {
                 i++;
                 if (i >= args.length) usage();
//                 filter = new EndsWithFilter(args[i]);
                 extension = args[i];
               }
             if (args[i].equals("-bd"))
               {
                 i++;
                 if (i >= args.length)
                   {}
                 else
                   directory = args[i];
               }
             if (args[i].equals("-d"))
               {
                 dodirs = true;			//set directory flag
               }  
           }
    if (directory == null) directory = System.getProperty("user.dir");
    
//    System.out.println(directory);
        
 
//                System.out.println(Replace(line, args[0], args[1]));
      p = new procdir(directory, extension, args[0], args[1], dodirs);

      }
  }
