The last several chapters have shown you how to read and write Java’s fundamental data types (
String, etc.). However, there’s been one glaring omission. Java is an object-oriented language, and yet aside from the special case of strings, you haven’t seen any general-purpose methods for reading or writing objects.
first used in the context of Remote Method Invocation (RMI) and later for JavaBeans, addresses this need. The
java.io.ObjectOutputStream class provides a
writeObject( ) method you can use to write a Java object onto a stream. The
java.io.ObjectInputStream class has a
readObject( ) method that reads an object from a stream.
ObjectOutputStream implement the
DataOutput interfaces respectively so they can also write primitive data types such as ints, floats, and doubles, In this chapter you’ll learn how to use these two classes to read and write objects as well as how to customize the format used for serialization.
Object serialization saves an object’s state in a sequence of bytes so that the object can be reconstituted from those bytes at a later time. Serialization in Java was first developed for use in RMI. RMI allows an object in one virtual machine to invoke methods in an object in another virtual machine, possibly in a different computer on the other side of the planet, by sending arguments and return values across the Internet. This requires ...