/** * 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 implements Serializable { 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 SerializeArray { 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")); dos.writeObject(f); 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 = (Foo[]) ois.readObject(); // print out the ones we got for ( int i=0;i