Objectinput Java Help

Objectinput

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.

ObjectinputStream

The ObjectInputStream class extends the InputStream class and implements the, ObjectInput interface, ObjectInputStream is responsible for reading objects from a stream. The constructor of this class.

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.

Serialization Example

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:

Stream Benefits

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.

JavaHelpOnline.com

  • Feel free to send us an inquiry, we will reply back in hours.
 

Verification

Posted on September 18, 2014 in Input/output: Exploring java.io

Share the Story

About the Author

Back to Top
Share This