

// file copy program, copying the first argument to the second

// the third argument, if `a', means append; `w' or lack of a third
// argument, means copy to a new file; if file already exists, program
// exits without copy

// reads in byte-by-byte; more advanced forms may be more efficient

import java.io.*;

public class CpBytes 

{
   public static void main (String Arg[]) throws FileNotFoundException,
      IOException
	
   {  // first, open the input file for reading; use the version of
      // FileInputStream() which has the file name as argument
      FileInputStream F1 = new FileInputStream(Arg[0]);
      
      // next, check to see if the output file already exists
      File F2Tmp = new File(Arg[1]);
      if (F2Tmp.exists() && Arg[2].equals("w"))  {
            System.out.println("file exists");
            System.exit(1);
      }

      // OK, now get the output file ready
      FileOutputStream F2;
      if (Arg.length == 2 || Arg[2].equals("w"))
         // FileOutputStream allows a descriptor from File
         F2 = new FileOutputStream(F2Tmp);
      else
         // but not if we are doing append
         F2 = new FileOutputStream(Arg[1],true);

      // now, the copying
      int ByteValue;  // has range 0 to 255, so it works for any type
                      // of data
      while (true)  {
         ByteValue = F1.read();
         if (ByteValue == -1)  // end-of-file encountered
            break;
         else F2.write(ByteValue);
      }
      // they would close when the program ended even without these
      // calls to close(), but let's put them in for thoroughness
      F1.close();
      F2.close();
   }
}


