Method One:
Implement the Serializable interface, I'm not going to say much.
Method Two:
Implement the Externalizable interface:
Example:
Packagedemo;Importjava.io.Externalizable;Importjava.io.IOException;ImportJava.io.ObjectInput;ImportJava.io.ObjectOutput; Public classXXSImplementsexternalizable{PrivateString name; Private intAge ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } Public voidWriteexternal (ObjectOutput out)throwsIOException {out.writeobject ( This); } Public voidReadexternal (ObjectInput in)throwsIOException, ClassNotFoundException {in.readobject (); }}
Test:
ImportJava.io.FileOutputStream;ImportJava.io.ObjectOutputStream; Public classDemo11 { Public Static voidMain (string[] args)throwsException {XXS XXS=NewXXS (); Xxs.setname (Hello); Xxs.setage (10); ObjectOutputStream dos=NewObjectOutputStream (NewFileOutputStream ("Xx.txt")); Dos.writeobject (XXS); Dos.close (); }}
Some APIs:
The only attribute of the Externalizable instance class is that it can be written to the serialized stream, which is responsible for saving and recovering the instance content. If you want to fully control the flow format and content of an object and its super-type, it implements the Writeexternal and Readexternal methods of the Externalizable interface. These methods must be explicitly reconciled with the superclass to hold their state. These methods are implemented in lieu of custom writeobject and ReadObject methods.
writeexternal (objectoutput out )
The object implements the Writeexternal method to hold its contents, and it can either save its base value by calling DataOutput's method, or call ObjectOutput's WriteObject method to hold objects, strings, and arrays.
readexternal (objectinput in )
The Readexternal object implements the method to restore its contents by invoking the Datainput method to restore its underlying type, calling ReadObject to recover objects, strings, and arrays.
ObjectInput:
The objectinput expands the Datainput interface to contain read operations for the object. Datainput includes basic types of input methods, and ObjectInput extends the interface to include objects, arrays, and String output methods.
Two ways to implement serialization in Java Serializable interface and externalizable interface