An ObjectOutputStream writes Serializable objects to an output stream. It is a high - level
stream that needs to be chained to a low - level stream that represents the destination of the
serialized objects. The upcoming SerializeDemo program demonstrates using FileOutput-
Stream with ObjectOutputStream .
stream that needs to be chained to a low - level stream that represents the destination of the
serialized objects. The upcoming SerializeDemo program demonstrates using FileOutput-
Stream with ObjectOutputStream .
1. package com.sybex.io;
2.
3. import java.io.*;
4. import java.util.GregorianCalendar;
5.
6. public class SerializeDemo {
7. public static void main(String [] args) {
8. try {
9. GregorianCalendar bday1 =
10. new GregorianCalendar(1950, 3, 21);
11. GregorianCalendar bday2 =
12. new GregorianCalendar(1956, 5, 30);
13. Contact2 one = new Contact2(“Bugs Bunny”, 2214. 2025551212L, bday1, “Toontown”);
15. Contact2 two = new Contact2(“Daffy Duck”, 33,
16. 3035551212L, bday2, “Toontown”);
17.
18. File contactsFile = new File(“mycontacts.ser”);
19. FileOutputStream fos =
20. new FileOutputStream(contactsFile);
21. ObjectOutputStream out = new ObjectOutputStream(fos);
22.
23. out.writeObject(one);
24. out.writeObject(two);
25.
26. out.close();
27. fos.close();
28. }catch(IOException e) {
29. e.printStackTrace();
30. }
31. }
32. }
2.
3. import java.io.*;
4. import java.util.GregorianCalendar;
5.
6. public class SerializeDemo {
7. public static void main(String [] args) {
8. try {
9. GregorianCalendar bday1 =
10. new GregorianCalendar(1950, 3, 21);
11. GregorianCalendar bday2 =
12. new GregorianCalendar(1956, 5, 30);
13. Contact2 one = new Contact2(“Bugs Bunny”, 2214. 2025551212L, bday1, “Toontown”);
15. Contact2 two = new Contact2(“Daffy Duck”, 33,
16. 3035551212L, bday2, “Toontown”);
17.
18. File contactsFile = new File(“mycontacts.ser”);
19. FileOutputStream fos =
20. new FileOutputStream(contactsFile);
21. ObjectOutputStream out = new ObjectOutputStream(fos);
22.
23. out.writeObject(one);
24. out.writeObject(two);
25.
26. out.close();
27. fos.close();
28. }catch(IOException e) {
29. e.printStackTrace();
30. }
31. }
32. }
There is no output, but the SerializeDemo program does create a new fi le named my
contacts.ser that contains two serialized objects of type Contact2 . The lines of code
to focus on in this program are lines 23 and 24. Calling writeObject and passing in a
Contact2 reference serializes the object and writes it to the mycontacts.ser fi le.
contacts.ser that contains two serialized objects of type Contact2 . The lines of code
to focus on in this program are lines 23 and 24. Calling writeObject and passing in a
Contact2 reference serializes the object and writes it to the mycontacts.ser fi le.
No comments:
Post a Comment