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