In this example, a more complex object is used that includes two variables. Rather than write and read the object's variables individually, they are written and read collectively by writing and reading the object as a whole.
public class jbsBasicCO implements Serializable { public static void main ( String arg[] ) { jbsContentObject jbsCO = new jbsContentObject (); try { FileOutputStream fos = new FileOutputStream ( "testFile.dat" ); ObjectOutputStream oos = new ObjectOutputStream ( fos ); System.out.println ( "Write:" ); System.out.println ( " Host=" + jbsCO.getHost () ); System.out.println ( " Port=" + jbsCO.getPort ().toString() ); oos.writeObject ( jbsCO ); oos.flush (); oos.close (); } catch ( Exception e ) { System.out.println ( "Error in ObjectOutput" ); } try { FileInputStream fis = new FileInputStream ( "testFile.dat" ); ObjectInputStream ois = new ObjectInputStream ( fis ); jbsContentObject injbsCO = (jbsContentObject)ois.readObject (); ois.close (); System.out.println ( "Read:" ); System.out.println ( " Host=" + injbsCO.getHost () ); System.out.println ( " Port=" + injbsCO.getPort ().toString() ); } catch ( Exception e ) { System.out.println ( "Error in ObjectOutput" ); } } // end main } // end jbsBasicCO //**************************************** public class jbsContentObject extends Object implements Serializable { String host = "wwwj.cs.unc.edu"; Integer port = new Integer ( 8888 ); public String getHost () { return ( host ); } // end getHost () public Integer getPort () { return ( port ); } // end getPort () } // end jbsContentObject