/** * Title: SerializePlay * Description: Using Serializable interface and ObjectStreams * @author hollingd@cs.rpi.edu */ import java.io.*; // a base class that includes a couple of fields abstract class Base { int x; String name; Base() { x=0; name="noname"; } Base(int i, String s) { x=i; name=s; } } // a derived class that adds a new field and is serializable class Foo extends Base implements Serializable{ String fooString; Foo() { super(); fooString="nofoostring"; } Foo( int x, String n, String f) { super(x,n); fooString=f; } public String toString() { return "Foo:\n\tx: " + x + "\n\t" + "Name: " + name + "\n\t" + "FooString: " + fooString + "\n"; } } // a main and a couple of methods for playing with // serializeable objects. public class SerializePlay { static public void main(String []args) throws IOException,ClassNotFoundException{ // probably want to comment out one of these for testing write(); // read(); } // write() generates a list of 5 Foo objects and then writes // them to the file named "save" (as Objects) static public void write() throws IOException,ClassNotFoundException{ Foo[] f = new Foo[5]; for (int i=0;i<5;i++) { f[i] = new Foo(i,"my name is " + Integer.toString(i), "Foo # " + i); } for (int i=0;i<5;i++) { System.out.println(f[i]); } // create an ObjectOutputStream associated with the file "save" ObjectOutputStream dos = new ObjectOutputStream( new FileOutputStream("save")); // write each Foo object to the file for (int i=0;i<5;i++) { dos.writeObject(f[i]); } dos.close(); System.out.println("Done"); } // read() reads 5 Foo objects from the file "save" // and prints them out. static public void read() throws IOException,ClassNotFoundException{ ObjectInputStream ois = new ObjectInputStream( new FileInputStream("save")); Foo[] blah = new Foo[5]; int i=0; boolean done=false; // Use EOFException to control when the loop ends while (! done) { try { blah[i] = (Foo) ois.readObject(); System.out.println("Read one foo"); i++; } catch( EOFException e) { done=true; } } // print out the 5 we got. for ( i=0;i<5;i++) { System.out.println(blah[i]); } } }