Java Reference
In-Depth Information
The ObjectOutputStream constructor and all methods that write data to an object output
stream throw IOException objects. These must be accounted for using a try - catch
block or a throws clause.
Listing 16.1 contains a Java application that consists of two classes: ObjectWriter and
Message . The Message class represents an email message. This class has from and to
objects that store the names of the sender and recipient, a now object that holds a Date
value representing the time it was sent, and a text array of String objects that holds the
message. There also is an int called lineCount that keeps track of the number of lines
in the message.
16
When designing a program that transmits and receives email, it makes sense to use some
kind of stream to save these messages to disk. The information that constitutes the mes-
sage must be saved in some form as it is transmitted from one place to another; it also
might need to be saved until the recipient is able to read it.
Messages can be preserved by saving each message element separately to a byte or char-
acter stream. In the example of the Message class, the from and to objects could be writ-
ten to a stream as strings, and the text object could be written as an array of strings. The
now object is a little trickier because there isn't a way to write a Date object to a charac-
ter stream. However, it could be converted into a series of integer values representing
each part of a date: hour, minute, second, and so on. Those could be written to the
stream.
Using an object output stream makes it possible to save Message objects without first
translating them into another form.
The ObjectWriter class in Listing 16.1 creates a Message object, sets up values for its
variables, and saves it to a file called Message.obj via an object output stream.
LISTING 16.1
The Full Text of ObjectWriter.java
1: import java.io.*;
2: import java.util.*;
3:
4: public class ObjectWriter {
5: public static void main(String[] arguments) {
6: Message mess = new Message();
7: String author = “Sam Wainwright, London”;
8: String recipient = “George Bailey, Bedford Falls”;
9: String[] letter = { “Mr. Gower cabled you need cash. Stop.”,
10: “My office instructed to advance you up to twenty-five”,
11: “thousand dollars. Stop. Hee-haw and Merry Christmas.” };
12: Date now = new Date();
13: mess.writeMessage(author, recipient, now, letter);
Search WWH ::




Custom Search