The Java Program: RandomStructure.java
1 // RandomStructure.java
2
3 import java.io.Serializable;
4 import java.io.FileOutputStream;
5 import java.io.FileInputStream;
6 import java.io.ObjectOutputStream;
7 import java.io.ObjectInputStream;
8 import java.io.IOException;
9 import java.io.FileNotFoundException;
10 import java.io.NotSerializableException;
11 import java.io.StreamCorruptedException;
12 import java.io.OptionalDataException;
13 import java.util.Date;
14
15
16 public class RandomStructure implements Serializable {
17
18 private static int r() { return (int)(Math.random()*100); }
19 private int [] junk = { r(), r(), r() }; // Some data in the structure
20
21 private RandomStructure link; // Structure with pointers
22 private RandomStructure self;
23 private char name;
24
25 RandomStructure () {} // Required of serialized objects
26
27 RandomStructure (int i, char n) {
28 name = n;
29 if (i>1) link = new RandomStructure (i-1, (char)(n+1));
30 self = this; // Try to fool serialization with circular pointers
31 }
32
33 // A printable representation of this data structure
34 public String toString () {
35 String s = name + ":";
36 for (int i=0;i<junk.length;i++) {
37 s += junk[i]+(i==junk.length-1?"":",");
38 }
39 if (link!=null) {
40 s += " -> " + link.toString();
41 }
42 return s;
43 }
44
45 public static void main (String args[]) {
46 RandomStructure s = new RandomStructure (5, 'a');
47 System.out.println (s);
48
49 // Write the object and some other things
50 try {
51 ObjectOutputStream oo =
52 new ObjectOutputStream (new FileOutputStream("s.ser"));
53 oo.writeObject (new Date ());
54 oo.writeDouble (Math.random());
55 oo.writeObject (s);
56 oo.flush();
57 oo.close();
58 } catch (FileNotFoundException e) {
59 e.printStackTrace ();
60 } catch (NotSerializableException e) {
61 e.printStackTrace ();
62 } catch (IOException e) {
63 e.printStackTrace ();
64 }
65
66 // Read the object with the other things
67 try {
68 ObjectInputStream oi =
69 new ObjectInputStream (new FileInputStream("s.ser"));
70 System.out.println ((Date) oi.readObject());
71 System.out.println (oi.readDouble());
72 System.out.println ((RandomStructure) oi.readObject());
73 } catch (FileNotFoundException e) {
74 e.printStackTrace ();
75 } catch (ClassNotFoundException e) {
76 e.printStackTrace ();
77 } catch (StreamCorruptedException e) {
78 e.printStackTrace ();
79 } catch (OptionalDataException e) {
80 e.printStackTrace ();
81 } catch (IOException e) {
82 e.printStackTrace ();
83 }
84 }
85 }