Java Reference
In-Depth Information
Code 12.24
Serialization of a com-
plete Address Book
with all Contact
Details
public class AddressBookFileHandler
{
. . . fields and methods omitted . . .
/**
* Save a binary version of the address book to the given file.
* If the file name is not an absolute path, then it is assumed
* to be relative to the current project folder.
* @param destinationFile The file where the details
* are to be saved.
* @throws IOException If the saving process fails for any reason.
*/
public void saveToFile(String destinationFile) throws IOException
{
File destination = makeAbsoluteFilename(destinationFile);
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream
(destination));
os.writeObject(book);
os.close();
}
}
Exercise 12.52 Modify the network project from Chapter 9 so that the data can be stored to
a file. Use object serialization for this. Which classes do you have to declare to be serializable?
Exercise 12.53 What happens if you change the definition of a class by, say, adding an extra
field and then try to read back serialized objects created from the previous version of the class?
12.10
Summary
When two objects interact, there is always the chance that something could go wrong, for a
variety of reasons. For instance:
The programmer of a client might have misunderstood the state or the capabilities of a par-
ticular server object.
A server object may be unable to fulfill a client's request because of a particular set of exter-
nal circumstances.
A client might have been programmed incorrectly, causing it to pass inappropriate parameter
values to a server method.
If something does go wrong, a program is likely either to terminate prematurely (i.e., crash!) or
to produce incorrect and undesirable effects. We can go a long way toward avoiding many of
 
 
Search WWH ::




Custom Search