public class ClassObjectIODemo
1: //ClassObjectIODemo.java
2:
3: import java.io.FileInputStream;
4: import java.io.FileOutputStream;
5: import java.io.IOException;
6: import java.io.ObjectInputStream;
7: import java.io.ObjectOutputStream;
8:
9: public class ClassObjectIODemo
10: {
11: public static void main(String[] args)
12: {
13: ObjectOutputStream outputStream = null;
14: String fileName = "species.records";
15: try
16: {
17: outputStream =
18: new ObjectOutputStream(new FileOutputStream(fileName));
19: }
20: catch (IOException e)
21: {
22: System.out.println("Error opening output file " + fileName + ".");
23: System.exit(0);
24: }
25: Species califCondor = new Species("Calif. Condor", 27, 0.02);
26: Species blackRhino = new Species("Black Rhino", 100, 1.0);
27: try
28: {
29: outputStream.writeObject(califCondor);
30: outputStream.writeObject(blackRhino);
31: outputStream.close();
32: }
33: catch (IOException e)
34: {
35: System.out.println("Error writing to file " + fileName + ".");
36: System.exit(0);
37: }
38: System.out.println("Records sent to file " + fileName + ".");
39: System.out.println("Now let's reopen the file and echo the records.");
40: ObjectInputStream inputStream = null;
41: try
42: {
43: inputStream =
44: new ObjectInputStream(new FileInputStream("species.records"));
45: }
46: catch (IOException e)
47: {
48: System.out.println("Error opening input file " + fileName + ".");
49: System.exit(0);
50: }
51: Species readOne = null, readTwo = null;
52: try
53: {
54: readOne = (Species)inputStream.readObject();
55: readTwo = (Species)inputStream.readObject();
56: inputStream.close();
57: }
58: catch (Exception e)
59: {
60: System.out.println("Error reading from file " + fileName + ".");
61: System.exit(0);
62: }
63: System.out.println("The following were read\n"
64: + "from the file " + fileName + ".");
65: System.out.println(readOne);
66: System.out.println();
67: System.out.println(readTwo);
68: System.out.println("End of program.");
69: }
70: }