// simple command-line tool for adding and looking up names in a phone book // // to build: // javac Phones.java // to run: // java Phones add zoe 555-9876 // java Phones get zoe // java Phones get rich // import java.io.*; import java.util.*; public class Phones { public static void main(String[] args) { // debug code to print the command-line arguments: // echoArgs(args); 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 ( ObjectInputStream p = new ObjectInputStream(new FileInputStream(filename)) ) { bk = (PhoneBook)p.readObject(); } catch ( IOException e ) { // file not found, just return a null so that the application // creates the file for future runs 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( ObjectOutputStream p = new ObjectOutputStream(new FileOutputStream(filename)) ) { p.writeObject(bk); } 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]); } }