import java.io.*; class ObjectToSave implements Serializable { static final long serialVersionUID = 7482918152381158178L; private int i; private String s; private transient double d; public ObjectToSave( int i, String s, double d ) { this.i = i; this.s = s; this.d = d; } public String toString() { return "i = " + i + ", s = " + s + ", d = " + d; } private void readObject( ObjectInputStream ois ) throws ClassNotFoundException, IOException { System.out.println( "deserializing..." ); ois.defaultReadObject(); System.out.println( "deserialized" ); } private void writeObject( ObjectOutputStream oos ) throws IOException { System.out.println( "serializing..." ); oos.defaultWriteObject(); System.out.println( "serialized" ); } } public class ObjectSaver { private static final String FILE_NAME = "objects.ser"; public static void main( String[] args ) { try { ObjectToSave ots = new ObjectToSave( 57, "pizza", 3.14 ); File objectFile = new File( FILE_NAME ); if ( objectFile.exists() ) { objectFile.delete(); } FileOutputStream fos = new FileOutputStream( objectFile ); ObjectOutputStream oos = new ObjectOutputStream( fos ); oos.writeObject( ots ); oos.close(); FileInputStream fis = new FileInputStream( objectFile ); ObjectInputStream ois = new ObjectInputStream( fis ); ObjectToSave retrieved = (ObjectToSave) ois.readObject(); ois.close(); System.out.println( retrieved ); } catch ( OptionalDataException x ) { System.out.println( x ); x.printStackTrace(); } catch ( ClassNotFoundException x ) { System.out.println( x ); x.printStackTrace(); } catch ( IOException x ) { System.out.println( x ); x.printStackTrace(); } } }