Serialization and deserialization

Source: Internet
Author: User

To enable an object to support serialization, you must make its class serializable. That is, this class must implement one of two interfaces: serializable and externalizable.

Serializable is a flag interface that does not need to implement any methods. It only indicates that the instance of this class is serializable.

Class to implement the serializable interface, you can serialize the object of this class.

Procedure:

1. Create an objectoutputstream. The output stream is a processing stream, so it must be built on the basis of other node streams.

Objectoutputstream OOS = new objectoutputstream (New fileoutputstream ("object.txt "));

2. Call the writeobject method of the objectoutstream object to output the serializable object.

Person = new person (11, "AAA", 22 );

Oos. Write (person );

Restore Java objects from binary streams through deserialization

Procedure:

1. Create an objectinputstream. The input stream is a processing stream, which must be based on the stream of other nodes.

Objectinputstream OIS = new objectinputstream (New fileinputstream ("object.txt "));

2. Call the readobfect method of the objectinputstream object to read objects in the stream.

Person P = (person) Ois. readobject ();

Note: deserialization only reads the data of Java objects, rather than Java classes. When deserialization is used to restore a Java object, class files of the classes to which the Java object belongs must be provided, otherwise, a classnotfoundexception exception is thrown.

If multiple Java objects are written to a file using a serialized part, the object must be read in the actual write order when the deserialization mechanism is used to restore the object.

----------------- Excerpt from crazy Java handout

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.