// simple command-line tool for adding and looking up names in a phone book // // to build: // javac -source 1.4 Phones.java // to run: // java -ea Phones add zoe 555-9876 // java -ea Phones get zoe // java -ea Phones get rich // import java.io.*; import java.util.*; // java Phones add [name] [number] // java Phones get [name] public class Phones { public static void main(String[] args) { // echoArgs(args); // for debugging PhoneBook book; if ( args.length < 2 ) post_usage("Missing add or get command and name"); String name = args[1]; book = load("phone-book.dat"); if ( book == null ) // no file, create object book = new PhoneBook(); String cmd = args[0]; if ( cmd.equals("add") ) { if ( args.length < 3 ) post_usage("Missing phone number"); String phone = args[2]; if ( book.contains(name) ) book.changeEntry(name, phone); else book.addEntry(new PhoneEntry(name, phone)); save(book, "phone-book.dat"); } else if( cmd.equals("get") ) { String phone = book.lookupNumber(name); if ( phone == null ) { System.out.println("No phone entry for " + name); System.exit(1); } else System.out.println("Phone # for " + name + ": " + phone); } else post_usage("First argument must be add or get; got " + cmd); } protected static void post_usage(String msg) { System.out.println("Usage: java Phones add|get name [number]"); System.out.println(msg); System.exit(1); } protected static PhoneBook load(String filename) { PhoneBook bk = null; try { FileInputStream istream = new FileInputStream(filename); ObjectInputStream p = new ObjectInputStream(istream); bk = (PhoneBook)p.readObject(); istream.close(); } catch ( IOException e ) { // file not found, just return a null return null; } catch ( ClassNotFoundException e ) { System.err.println("Data file " + filename + " contains wrong class."); System.exit(1); } return bk; } protected static void save(PhoneBook bk, String filename) { try { FileOutputStream ostream = new FileOutputStream(filename); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeObject(bk); p.flush(); ostream.close(); } catch ( IOException e ) { System.err.println("Could not save phone book to " + filename); } } protected static void echoArgs(String[] args) { System.out.println("Number of command-line arguments: " + args.length); for(int i = 0; i < args.length; ++i) System.out.println("args[" + i + "] = " + args[i]); } }