The Java serialization and deserialization operations are analyzed in the example. Share to everyone for your reference, specific as follows:
Overview:
Java serialization refers to the process of converting a Java object into a sequence of bytes, while Java deserialization refers to the process of restoring a byte sequence to a Java object.
Sample code:
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import java.io.Serializable;
Import java.util.ArrayList;
Import Java.util.Date;
Import Java.util.HashMap;
Import java.util.List; public class Test {/** * @param args */public static void main (string[] args) {try {objectoutputst
Ream out = new ObjectOutputStream (New FileOutputStream ("D:/objectfile.obj"));
Customer customer = new Customer ("Chinese", 23);
Out.writeobject ("Hello!");
Out.writeobject (New Date ());
Out.writeobject (customer);
Out.writeint (123);
List List = new ArrayList ();
int i = 0;
while (i<100) {Customer customer2 = new Customer ("Chinese", I);
List.add (CUSTOMER2);
i++;
} HashMap HashMap = new HashMap ();
Hashmap.put ("Customer", list);
Out.writeobject (HASHMAP); Out.cLose ();
ObjectInputStream in = new ObjectInputStream (New FileInputStream ("D:/objectfile.obj"));
System.out.println ("obj1=" + (String) in.readobject ());
System.out.println ("obj2=" + (Date) in.readobject ());
Customer OBJ3 = (customer) in.readobject ();
System.out.println ("obj3=" + obj3);
int obj4 = In.readint ();
System.out.println ("obj4=" + obj4);
Object obj5 = In.readobject ();
System.out.println (OBJ5);
HashMap hash_map = (HashMap) obj5;
List L = (list) Hash_map.get ("Customer");
SYSTEM.OUT.PRINTLN ("Size:" + l.size ());
for (int ii=0; ii<l.size ()-1; ii++) {Customer c = (customer) l.get (ii);
System.out.println (C.getname ());
System.out.println (C.getage ());
} in.close ();
catch (FileNotFoundException e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
catch (ClassNotFoundException e) {e.printstacktrace (); }} CLAss Customer implements Serializable {private static final long serialversionuid = 1L;
private String name;
private int age;
Public String GetName () {return name;
public int getage () {return age;
Public Customer (String name, int age) {this.name = name;
This.age = age;
Public String toString () {return ' name= ' + name + ', age= ' + age;
}
}
I hope this article will help you with your Java programming.