Chapter 15

Serialization

Interoperation between a client and server can be separated into two distinct parts: how the data is transmitted, and what is transmitted. The previous chapter gave one method for how to transmit and receive data, and this chapter explains different methods for representing your data over that transmission.

The methods here are not specific to network communication. Object serialization is simply a way of “exporting” Java objects from the JVM: The serialized data can be written to disk or another I/O interface rather than to the network.

For convenience, most of the listings in this chapter read and write serialized data to and from the filesystem, using FileInputStreams and FileOutputStreams. These can be substituted for any InputStream and OutputStream, such as the ones provided by HttpServletRequest and HttpServletResponse if you wanted to use the data in an HTTP server.

Reading and Writing Java Objects

What does the JVM provide for writing objects to a third party?

The standard Java libraries provide a pair of classes for writing and reading Java objects: ObjectOutputStream and ObjectInputStream. These are part of the InputStream and OutputStream family of classes.

For writing objects, ObjectOutputStreams are constructed using the Decorator Pattern, and require another OutputStream to physically write the serialized data. The ObjectOutputStream class has methods for all the primitive types, as well as a method for reference types, for writing ...

Get Java Programming Interviews Exposed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.