// COBOL Programmers Swing With Java - copyright 2005 Doke, Hardgrave, & Johnson // Chapter 9 - Data Access // Program to demonstrate Object Persistence using Serialization // ObjectSerializationDemo.java 1 JAN 05 import java.io.*; public class ObjectSerializationDemo { public static void main (String args[]) // main is first method executed { // create a File instance for Customer.dat File customerFile = new File ("C:/Temporary/Customer.dat"); // create two customer instances String name = "Jed Muzzy"; String ssNo = "499444471"; String address = "P.O. Box 1881, Great Falls, MT 59601"; String phoneNumber = "None"; Customer customer1 = new Customer(name, ssNo, address, phoneNumber); name = "Bill Sinclair"; ssNo = "491446543"; address = "General Delivery, Pender Harbor, BC, Canada"; phoneNumber = "441-8970"; Customer customer2 = new Customer(name, ssNo, address, phoneNumber); // and store them in "CustomerFile" try { FileOutputStream f = new FileOutputStream (customerFile); ObjectOutputStream o = new ObjectOutputStream (f); o.writeObject(customer1); o.writeObject(customer2); } catch (Exception event) {System.out.println ("I/O error during write to CustomerFile");} // now read them back - Note customer1 is now Bill) try { FileInputStream f = new FileInputStream (customerFile); ObjectInputStream i = new ObjectInputStream (f); customer2 = (Customer) i.readObject(); customer1 = (Customer) i.readObject(); } catch (Exception event) {System.out.println ("I/O error during read from CustomerFile");} // now display the attributes from retrieved customer instances System.out.println ("Name: " + customer1.getName()); System.out.println ("SS No: " + customer1.getSSNo()); System.out.println ("Address: " + customer1.getAddress()); System.out.println ("Phone: " + customer1.getPhoneNumber()); System.out.println ("Name: " + customer2.getName()); System.out.println ("SS No: " + customer2.getSSNo()); System.out.println ("Address: " + customer2.getAddress()); System.out.println ("Phone: " + customer2.getPhoneNumber()); } } // end of ObjectSerializationDemo.java