How to Learn the serialization of 9--io in CoreJava

Source: Internet
Author: User
Tags object serialization

Java serialization

Serialization) is a process of describing objects in a series of bytes. deserialization is a process of recreating these bytes into an object.

Java serialization API provides a standard mechanism for processing object serialization.

In Java, everything is an Object. In a distributed environment, it is often necessary to pass an Object from this network or device to the other end. This requires a protocol that can transmit data at both ends. Java serialization mechanism is generated to solve this problem.


If our object needs to be serialized, we need to implement the Serializable interface of the serialization interface. The Serializable interface has no method, more like a mark. The Class with this mark can be processed by the serialization mechanism.

Serialization:

1) The data stored in this object must be used all the time. We can serialize the data and write it to the hard disk for long-term storage. We can continue to use it after the next program starts.

2) network transmission of objects.

Principle:

Converting an Object to a byte series is serialization, and vice versa.

To store objects in byte streams.

Use writeObject (Object)/readObject () for serialization and deserialization.


The serian specification must implement the Serializable interface. Java API classes are mostly JavaBean and basically all implement Serializable.


1. ObjectOutputStream (serialization) and ObjectInputStream (deserialization)

If the Serializable interface is not implemented, an exception occurs during serialization.

Example:


Public class Demo2_Serializable {public static void main (String [] args) throws Exception {// serializable (); noSerializable ();} /** deserialization */public static void noSerializable () throws IOException, Exception {ObjectInputStream ois = null; try {FileInputStream FD = new FileInputStream ("person. obj ");/** use ObjectInputStream deserialization */ois = new ObjectInputStream (FS);/** read bytes and convert them to objects, forced conversion, if there are multiple entries in serialized order Get the object in sequence */Persons person = (Persons) ois. readObject (); Persons person1 = (Persons) ois. readObject (); System. out. println (person); System. out. println (person1);} finally {if (ois! = Null) {ois. close () ;}}/** serialization */public static void serializable () throws IOException {Persons person = new Persons ("boss", "123456 ); persons person1 = new Persons ("Andy Lau", "123456 ); /*** Save the object in the file. * 1. Create the byte output stream FileOutputStream for writing the file * 2. Create the ObjectOutputStream for serializing the object and let it process FileOutputStream, in this way, the object can be serialized into bytes without being saved to the file. * 3. Use ObjectOutputStream to write the object. */ObjectOutputStream oos = null; try {FileOutputStream fos = new FileOutputStream ("person. obj "); oos = new ObjectOutputStream (fos); // write to the file oos after serialization. writeObject (person); oos. writeObject (person1);/*** Note: only attribute values are written, but the total number of bytes actually written is larger than the total number of bytes of all attribute values. */} Finally {if (oos! = Null) {oos. flush (); oos. close () ;}}} class Persons implements Serializable {private String name; private String password; private int age; private int sex; public String getName () {return name ;} public void setName (String name) {this. name = name;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public int getSex () {return sex;} public void setSex (int sex) {this. sex = sex;} public Persons (String name, String password, int age, int sex) {super (); this. name = name; this. password = password; this. age = age; this. sex = sex;} public Persons () {super () ;}@ Override public String toString () {return "Persons [name =" + name + ", password = "+ password +", age = "+ age +", sex = "+ sex +"] ";}


2. Keyword tarnsient


Tarnsient is a java keyword used to indicate that a domain is not a part of the object's serialization. when an object is serialized, the value of the tarnsient variable is not included in the serialized representation, however, variables other than the tarnsient type are included.


The deserialized objects are true compared with the original object equals, but they are not the same object. If the attributes are of the reference type, these attributes are not the same object, however, equals is also true.


4. ByteArrayInputStream and ByteArrayOutStream


Both have clear source and destination, and the two streams maintain this byte array. The read and write operations are performed on the internal maintenance array.


/***** Deeply copy Object */public static Object deepClone (object Object) {try {/*** 1. Create byte input stream ByteArrayOutputStream * for writing bytes into byte arrays. 2. Create and process ObjectOutputStream for serializing objects. * 3. When an object is written by oos, in fact, ByteArrayOutputStream is written to the Internally maintained byte array. We get this array * 4. Create an input stream ByteArrayInputStream for reading data from the array, * The serialized byte array of the previously stored object is passed to the stream. * 5. Create an ObjectInputStream for deserializing objects and process ByteArrayInputStream * 6. Use OIS to read and deserialize objects to reach the directory of deep replication. */ByteArrayOutputStream baos = new ByteArrayOutputStream (); // 1 ObjectOutputStream oos = new ObjectOutputStream (baos); // 2 oos. writeObject (object); // 3 // obtain the maintained array byte [] data = baos. toByteArray (); // 4 convert to input stream ByteArrayInputStream bais = new ByteArrayInputStream (data); // 5 ObjectInputStream ois = new ObjectInputStream (bais); // 6 Object copy = ois. readObject (); oos. close (); ois. close (); return copy;} catch (Exception e) {e. printStackTrace (); throw new RuntimeException (e) ;}} public static void main (String [] args) {Persons person = new Persons ("Wu", "2332523 ", 2332523); Persons person1 = new Persons ("Wu g", "",); ArrayList <Persons> list = new ArrayList <Persons> (); list. add (person); // list. add (person); ArrayList <Persons> list2 = (ArrayList <Persons>) deepClone (list); // System. out. println (list. get (0) = list. get (1); System. out. println (list = list2); System. out. println (list. get (0) = list2.get (0); System. out. println (list. get (0 ). equals (list2.get (0 )));}



In addition, for the principle of Java serialization algorithm Dialysis can refer to the http://developer.51cto.com/art/200908/147650.htm

This article from the "beautiful life needs to carefully record" blog, please be sure to keep this http://huing.blog.51cto.com/1669631/1295135

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.