Learning Java for so long, although the brain of the understanding of serialization, but not actually applied, just met a friend to help do a homework, take the opportunity to write a very simple example.
Import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.objectinputstream There are two main uses for serialization of;import java.io.objectoutputstream;import java.io.serializable;/** * objects: 1) Permanently save the byte sequence of the object to the hard disk, usually in a file, 2) The byte sequence that transmits the object on the network. *//** * to serialize an object, the object inherits the Java.io.Serializable class. *//** * @author Jim * @Time 2016 April 14 PM 1:47:48 * */public class program21 {public static void main (String[] args) {try{//serialized object, Save the object in Student.dat Objectoutputstream out = new objectoutputstream (new FileOutputStream ("Student.dat")); Student s1 = new student ("Lisa", 20); Out.writeobject (S1);//write to Object Out.close ();// Deserializes the objects in the Student.dat and print information them. Objectinputstream in = new objectinputstream (New fileinputstream ("Student.dat")); student s2 = (Student) in.readobject ();//read out the object syStem.out.print ("Student ' s name is " + s2.getname () + " and the age is " + s2.getage ()); In.close ();} catch (exception e) {e.printstacktrace ();}}} /** * defines a student class to inherit java.io.serializable */class student implements serializable {private String name = "";p rivate int age = 0;public Student (String name, int age) {this.name = name;this.age = age;} Public string getname () {return this.name;} Public int getage () {return this.age;}}
This article is from the "a&d_ro535" blog, make sure to keep this source http://ro535.blog.51cto.com/11279790/1763771
An example of Java serialization