1  import java.io.File;
  2  import java.io.FileNotFoundException;
  3  import java.io.PrintWriter;
  4  import java.util.Scanner;
  5  
  6  /**
  7     This program encrypts a file using the Caesar cipher.
  8  */
  9  public class CaesarCipher
 10  {  
 11     public static void main(String[] args) throws FileNotFoundException
 12     {  
 13        final int DEFAULT_KEY = 3;
 14        int key = DEFAULT_KEY;
 15        String inFile = null;
 16        String outFile = null;
 17  
 18        for (int i = 0; i < args.length; i++)
 19        {  
 20           String arg = args[i];
 21           if (arg.charAt(0) == '-')
 22           {  
 23              // It is a command line option
 24  
 25              char option = arg.charAt(1);
 26              if (option == 'd') { key = -key; }
 27              else { usage(); return; }
 28           }
 29           else
 30           {  
 31              // It is a file name
 32  
 33              if (inFile == null) { inFile = arg; }
 34              else if (outFile == null) { outFile = arg; }
 35              else { usage(); return; }
 36           }
 37        }
 38        if (inFile == null || outFile == null) { usage(); return; }
 39  
 40        Scanner in = new Scanner(new File(inFile));
 41        in.useDelimiter(""); // Process individual characters
 42        PrintWriter out = new PrintWriter(outFile);
 43        while (in.hasNext())
 44        {
 45           char from = in.next().charAt(0);
 46           char to = (char) (from + key);
 47           out.print(to);
 48        }
 49        in.close();
 50        out.close();               
 51     }   
 52  
 53     /**
 54        Prints a message describing proper usage.
 55     */
 56     public static void usage()
 57     {  
 58        System.out.println("Usage: java CaesarCipher [-d] infile outfile");
 59     }
 60  }