Writing Serialized Data


ObjectOutputStream out =    new ObjectOutputStream(socket.getOutputStream()); out.writeObject(myObject);



Java enables object instances to be serialized and written either to a file or across a network. In this phrase, we show how you can write a serialized object to a network socket. This phrase assumes that we've previously created a socket to the server with which we want to communicate. See the phrase "Contacting a Server" in this chapter for more details on creating the socket instance.

In this phrase, we call the getOutputStream() method of the socket instance to get a reference to the socket's output stream. Using this, we can instantiate an ObjectOutputStream instance. The ObjectOutputStream class is used to serialize primitive data and objects. We use the writeObject() method of the ObjectOutputStream to write an object to the stream.

All data fields that are non-transient and non-static will be preserved in the serialization and restored when the object is deserialized. Only objects that support the java.io.Serializable interface can be written to streams.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net