CaesarCipher.java.html

  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 = "";
 16        String outFile = "";
 17        int files = 0; // Number of command line arguments that are files
 18  
 19        for (int i = 0; i < args.length; i++)
 20        {  
 21           String arg = args[i];
 22           if (arg.charAt(0) == '-')
 23           {  
 24              // It is a command line option
 25  
 26              char option = arg.charAt(1);
 27              if (option == 'd') { key = -key; }
 28              else { usage(); return; }
 29           }
 30           else
 31           {  
 32              // It is a file name
 33  
 34              files++;
 35              if (files == 1) { inFile = arg; }
 36              else if (files == 2) { outFile = arg; }
 37           }
 38        }
 39        if (files != 2) { usage(); return; }
 40  
 41        Scanner in = new Scanner(new File(inFile));
 42        in.useDelimiter(""); // Process individual characters
 43        PrintWriter out = new PrintWriter(outFile);
 44  
 45        while (in.hasNext())
 46        {
 47           char from = in.next().charAt(0);
 48           char to = encrypt(from, key);
 49           out.print(to);
 50        }
 51        in.close();
 52        out.close();               
 53     }   
 54  
 55     /**
 56        Encrypts upper- and lowercase characters by shifting them
 57        according to a key.
 58        @param ch the letter to be encrypted
 59        @param key the encryption key
 60        @return the encrypted letter      
 61     */
 62     public static char encrypt(char ch, int key)
 63     {
 64        int base = 0;
 65        if ('A' <= ch && ch <= 'Z') { base = 'A'; }
 66        else if ('a' <= ch && ch <= 'z') { base = 'a'; }
 67        else { return ch; } // Not a letter
 68        int offset = ch - base + key;
 69        final int LETTERS = 26; // Number of letters in the Roman alphabet
 70        if (offset > LETTERS) { offset = offset - LETTERS; }
 71        else if (offset < 0) { offset = offset + LETTERS; }
 72        return (char) (base + offset);
 73     }
 74  
 75     /**
 76        Prints a message describing proper usage.
 77     */
 78     public static void usage()
 79     {  
 80        System.out.println("Usage: java CaesarCipher [-d] infile outfile");
 81     }
 82  }