previous | start | next

File Crypt.java

1 import java.io.File;
2 import java.io.IOException;
3
4 /**
5     A program to run the Caesar cipher encryptor with
6     command line arguments.
7 */
8 public class Crypt
9 {  
10    public static void main(String[] args)
11    {  
12       boolean decrypt = false;
13       int key = DEFAULT_KEY;
14       File inFile = null;
15       File outFile = null;
16
17       if (args.length < 2 || args.length > 4) usage();
18
19       try
20       {  
21          for (int i = 0; i < args.length; i++)
22          {  
23             if (args[i].charAt(0) == '-';)
24             {  
25                // it is a command line option
26                char option = args[i].charAt(1);
27                if (option == 'd')
28                   decrypt = true;
29                else if (option == 'k')
30                   key = Integer.parseInt(args[i].substring(2));
31             }
32             else
33             {  
34                // it is a file name
35                if (inFile == null)
36                   inFile = new File(args[i]);
37                else if (outFile == null)
38                   outFile = new File(args[i]);
39                else usage();
40             }
41          }
42          if (decrypt) key = -key;
43          Encryptor crypt = new Encryptor(key);
44          crypt.encryptFile(inFile, outFile);
45       }
46       catch (NumberFormatException exception)
47       {  
48          System.out.println("Key must be an integer: " + exception);
49       }
50       catch (IOException exception)
51       {  
52          System.out.println("Error processing file: " + exception);
53       }
54    }
55
56    /**
57        Prints a message describing proper usage and exits.
58     */
59    public static void usage()
60    {  
61       System.out.println
62          ("Usage: java Crypt [-d] [-kn] infile outfile");
63       System.exit(1);
64    }
65
66    public static final int DEFAULT_KEY = 3;
67 }


previous | start | next