First, there is a student class
The serializable interface is a labeled interface that is equivalent to a flag on a class that allows participation in serialization and deserialization
public class Student implements serializable{
private String name;
private int age;
private address address;
Public Student () {
}
Public Student (String name, int.) {
Super ();
THIS.name = name;
This.age = age;
}
Public Student (string name, Int. age, String state,string city,string Street) {
Super ();
THIS.name = name;
This.age = age;
this.address = new address (state,city,street);
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
@Override
Public String toString () {
TODO auto-generated Method Stub
return this.name + ":" + This.age + ":" + this.address; Overriding the ToString Method
}
}
Serialization of objects--outputs the object in binary form (no definite output to where)
Arraylist<student> al = new Arraylist<student> ();
Student stu0 = new Student ("HJ", 25, "Sichuan", "Chengdu", "Jiuyan Bridge third Arch");
Student stu1 = new Student ("YP", 27, "Sichuan", "Chengdu", "Jiuyan Bridge 2nd Arch");
Al.add (STU0);
Al.add (STU1);
ObjectOutputStream oos = null;
try {
Oos = new ObjectOutputStream (New FileOutputStream ("Student.data")); Docking of two channels
Oos.writeobject (AL);
} catch (FileNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
if (oos! = null) {
try {
Oos.close (); You must remember to close the channel when you're done
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Deserialization-Converts the input binary stream to an object (also a data source that is not sure of the binary stream)
Arraylist<student> al = null;
ObjectInputStream ois = null;
try {
Adorner mode used
OIS = new ObjectInputStream (New FileInputStream ("Student.data"));
Al = (arraylist<student>) ois.readobject ();
} catch (FileNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally{
if (ois! = null) {
try {
Ois.close ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
System.out.println (al.get (0));
System.out.println (Al.get (1)); print See effect
}
Serialization and deserialization