// Copyright 1997, MageLang Institute. import java.io.*; import java.util.Date; import java.util.Vector; import java.util.Enumeration; class TreeNode implements Serializable { Vector children; TreeNode parent; String name; public TreeNode(String s) { children = new Vector(5); name = s; } public void addChild(TreeNode n) { children.addElement(n); n.parent = this; } public String toString() { Enumeration e = children.elements(); StringBuffer buff = new StringBuffer(100); buff.append("[ " + name + " : "); while(e.hasMoreElements()) { buff.append(e.nextElement().toString()); } buff.append(" ] "); return buff.toString(); } } public class SerialTest { public static void main(String[] args) { // first build a tree TreeNode top = new TreeNode("top"); top.addChild(new TreeNode("left")); top.addChild(new TreeNode("right")); // print it out to see how it looks System.out.println("source tree: \n" + top.toString()); // now write the tree to a file, and read it back in again try { FileOutputStream fOut = new FileOutputStream("test.out"); ObjectOutput out = new ObjectOutputStream(fOut); out.writeObject(top); out.flush(); out.close(); FileInputStream fIn = new FileInputStream("test.out"); ObjectInputStream in = new ObjectInputStream(fIn); TreeNode n = (TreeNode)in.readObject(); in.close(); System.out.println("read tree: \n" + n.toString()); } catch (Exception e) { System.out.println("exception: " + e); } } }