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