PackageCn.stat.p2.demo;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream; Public classObjectdemo {/** * @paramargs *@throwsIOException *@throwsFileNotFoundException *@throwsclassnotfoundexception*/ Public Static voidMain (string[] args)throwsFileNotFoundException, IOException, classnotfoundexception {//TODO auto-generated Method StubReadObject (); //writeobject (); } Private Static voidReadObject ()throwsFileNotFoundException, IOException, classnotfoundexception {//TODO auto-generated Method StubObjectInputStream ois=NewObjectInputStream (NewFileInputStream ("Obj.txt")); Preson P=(Preson) ois.readobject (); System.out.print (P.getname ()+":"+p.getage ()); Ois.close (); } Public Static voidWriteObject ()throwsIOException, FileNotFoundException {objectoutputstream oos=NewObjectOutputStream (NewFileOutputStream ("Obj.txt")); //To serialize the alignment, be sure to implement the Serializable interfaceOos.writeobject (NewPreson ("Xiao Wang", 12)); Oos.close (); }}
PackageCn.stat.p2.demo;Importjava.io.Serializable; Public classPresonImplementsSerializable {//The serialization runtime is associated with each serializable class using a version number called Serialversionuid.//the sequence number is used during deserialization to verify that the sender and receiver of the serialized object have loaded a serialized-compatible class for the object. //if the receiver loads the serialversionuid of the object's class with a different version number than the corresponding sender's class,//the deserialization will cause invalidclassexception. A serializable class can be declared by declaring a field named "Serialversionuid"//(This field must be a static (static), final (final) long field) to explicitly declare its own serialversionuid: Private Static Final LongSerialversionuid = 42213123123L; PrivateString name; Private intAge ; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicPreson (String name,intAge ) { Super(); This. Name =name; This. Age =Age ; } }
Java-to-image serialization