public class TestData
1: //TestData.java
2:
3: import java.io.*;
4:
5: public class TestData
6: {
7: public static void main(String[] args)
8: {
9: Data data = new Data(1);
10:
11: try
12: {
13: //Create the object output stream
14: ObjectOutputStream objectOut =
15: new ObjectOutputStream(
16: new BufferedOutputStream(
17: new FileOutputStream("dataObjects.bin")));
18:
19: //Write three variants of the object to the file
20:
21: objectOut.writeObject(data); //Write object
22: System.out.println("1st Object written has value: " +
23: data.getValue());
24: data.setValue(2); //Modify the object
25: objectOut.reset();
26: objectOut.writeObject(data); //and write it again
27: System.out.println("2nd Object written has value: " +
28: data.getValue());
29: data.setValue(3); //Modify the object again
30: objectOut.reset();
31: objectOut.writeObject(data); //and write it once more
32: System.out.println("3rd Object written has value: " +
33: data.getValue());
34: objectOut.close(); //Close the output stream
35:
36: }
37: catch(IOException e)
38: {
39: e.printStackTrace(System.err);
40: System.exit(1);
41: }
42:
43: //Read the three objects back from the file
44: System.out.println("\nReading objects from the file: ");
45: try
46: {
47: ObjectInputStream objectIn =
48: new ObjectInputStream(
49: new BufferedInputStream(
50: new FileInputStream("dataObjects.bin")));
51:
52: Data data1 = (Data)objectIn.readObject();
53: Data data2 = (Data)objectIn.readObject();
54: Data data3 = (Data)objectIn.readObject();
55: System.out.println("1st object is " + (data1.equals(data2) ? ""
56: : "not ")
57: + "Equal to 2nd object.");
58: System.out.println("2nd object is " + (data2.equals(data3)? ""
59: : "not ")
60: + "Equal to 3rd object.");
61:
62: //Display object values
63: System.out.println("data1 = " + data1.getValue() +
64: " data2 = " + data2.getValue() +
65: " data3 = "+ data3.getValue());
66: objectIn.close(); //Close the input stream
67:
68: }
69: catch(ClassNotFoundException e)
70: {
71: e.printStackTrace(System.err);
72: System.exit(1);
73:
74: }
75: catch(IOException e)
76: {
77: e.printStackTrace(System.err);
78: System.exit(1);
79: }
80: }
81: }