/* Database : Manipulate a simple key:value "database" as a map. * * Parke Godfrey, 2009-2-18 * */ import java.io.*; import java.util.*; public class Database { @SuppressWarnings("unchecked") public static void main(String[] args) { final String DB = "db.ser"; // File to store the map. Scanner input = new Scanner(System.in); PrintStream output = System.out; Map db; // Try restoring DB fom previous run. // First, open the file. try { FileInputStream fis = new FileInputStream(DB); // Second, open an ObjectInputStream on the FileInputStream. try { ObjectInputStream inStr = new ObjectInputStream(fis); Object obj = inStr.readObject(); inStr.close(); if (obj instanceof HashMap) { db = (HashMap)obj; } else { output.println("Previous DB map not right type!"); db = new HashMap(); } } catch(Exception ex) { fis.close(); output.println(ex.getMessage()); output.println("Could not read in previous DB map."); db = new HashMap(); } } catch(Exception ex) { output.printf("Could not open \"%s\".\n", DB); db = new HashMap(); } // Read in commands and values from the terminal. output.println("Command:"); while (input.hasNextLine()) { String line = input.nextLine(); String cmd = line.replaceFirst("^([^ ]+).*$", "$1"); String key = line.replaceFirst("^[^ ]+[ ]*([^ ]*).*$", "$1"); String val = line.replaceFirst( "^[^ ]+[ ]*[^ ]*[ ]*([^ ]*).*$", "$1"); if (cmd.equals("put")) { db.put(key, val); output.printf("Added\n"); output.printf(" key = %s\n", key); output.printf(" val = %s\n", val); } else if (cmd.equals("get")) { val = db.get(key); if (val != null) { output.printf("Retrieved for \"%s\"\n", key); output.printf(" val = %s\n", val); } else { output.printf("Nothing stored for \"%s\"\n", key); } } else if (cmd.equals("clear")) { db.clear(); output.printf("Map cleared.\n"); } else { output.printf("Say what?\n"); } output.println(""); output.println("Command:"); } // Print out the contents of the map. Iterator keys = db.keySet().iterator(); String key; for (; keys.hasNext();) { key = keys.next(); output.printf("key = %s ", key); output.printf("val = %s\n", db.get(key)); } // Try saving DB from this run. try { ObjectOutputStream outStr = new ObjectOutputStream(new FileOutputStream(DB)); outStr.writeObject(db); outStr.flush(); outStr.close(); } catch(IOException ioe) { output.println(ioe.getMessage()); output.println("Could not save current DB."); } } }