The Object Input interface extends the DataInput interface and, defines the methods shown. It supports object serialization. Note especially the readObject method. This is called to deserialize an object. All of these methods will throw an IOException on error conditions.
The most commonly used methods in this-class are shown.They will throw an IOException on error conditions. Java 2 adds an inner class to ObjectInputStream called GetField. It facilitates the reading of persistent fields and its use is beyond the scope of this book. Also, the method realnet ) was deprecated by Java 2 and should no longer be used.
The following program illustrates how to use object serialization and deserialization.It begins by instantiating an object of class MyClass. isobject has three instance variables that are of types String, int, and double. This is the information we ‘want to save and restore.
A FileOutputStream is created that refers 10 a file named serial, and an ObjectOutputStream is created for that file stream. The writeObject( ) method of ObjectOutputStream is then used to serialize our object. The object output stream is flushed and closed.
Note that MyClass.is defined to implement the Serializable interface. If this is not done, aNotfierialtzableflxception is-thrown. Try experimenting with this program by declaring some of the MyClass instance variables to be transient 111a data is then not saved during serialization.
This program-demonstrates that the instance variables of objects and object2 are identical. The output is shown here:
The streaming interface to I/O in [ava provides LI clean abstraction for a complex and often cumbersome task.The composition of the filtered stream classes allows you to dynamically build the custom streaming interface to suit your data transfer requirements. Java programs written to adhere to.the abstract, high-level InputStream, Outputstream, Reader, and Writer classes will function properly in the future even when new and improved concrete stream classes are invented. As you will see in the next chapter, this model works very well when we switch from a file system-based set of streams to the network and socket streams. Finally, serialization of objects is expected to play an increasingly important role in Java programming in the future. Java’s serialization I/O classes provide a portable solution to this sometimes tricky task.