function : Used for persisting objects, writing objects to the hard disk, and then deserializing them when needed.
The so-called serialization is actually the data (objects) in the program in some way, saved to the local.
You can then save the program's execution state after the program is closed, to facilitate the next time the program
The execution is read by "deserialization", and the type of the data can be restored, thus perpetuating the state of the program when it exits.
In general, we use serialization to save some data that needs to be persisted, of course, if the data is quite large,
We're going to use the database directly! So, serialization is actually not much used in many areas, and most of it uses
have been replaced by the database!
How to serialize and deserialize:
Serialization through implementation of the Serializable interface
Public classPersonImplementsserializable{PrivateString name;PrivateString sex; PublicPerson (String name,string sex) { This. name=name; This. sex=sex;} PublicString GetName () {returnname;} Public voidsetName (String name) { This. Name =name;} PublicString Getsex () {returnsex;} Public voidsetsex (String sex) { This. Sex =sex;} }
Public classTestdemo { Public Static voidMain (string[] args) {//Create an ObjectPerson people =NewPerson ("Zhang San", "male"); Try { //instantiating a ObjectOutputStream objectObjectOutputStream Oos =NewObjectOutputStream (NewFileOutputStream ("C:\\person.txt")); //writing an object to a fileOos.writeobject (people); Oos.flush (); Oos.close ();//instantiating a ObjectInputStream objectObjectInputStream ois=NewObjectInputStream (NewFileInputStream ("C:\\person.txt")); Try { //Read object people, deserializationPerson p =(person) ois.readobject (); System.out.println ("Name:" +p.getname ()); System.out.println ("Gender:" +p.getsex ()); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blocke.printstacktrace ();} } Catch(FileNotFoundException e) {e.printstacktrace ();}Catch(IOException e) {//TODO auto-generated Catch blocke.printstacktrace ();} } }
Serialization of Java Classes