1 ImportJava.io.ByteArrayInputStream;2 ImportJava.io.ByteArrayOutputStream;3 ImportJava.io.ObjectInputStream;4 ImportJava.io.ObjectOutputStream;5 Importjava.io.Serializable;6 7 Public classUserImplementsSerializable {8 PrivateString username; 9 Ten Private transientString password; One A PublicUser (String username,string password) { - This. Username =username; - the This. Password =password; - } - - @Override + PublicString toString () { - returnUsername + "" +password; + } A at Public Static voidMain (string[] args)throwsexception{ -User User =NewUser ("Weidong", "123456"); - -System.out.println ("before serialization:" +user); - -Bytearrayoutputstream buf =NewBytearrayoutputstream (); in //creates an object output stream that WriteObject () writes objects to the output stream through the object output stream -ObjectOutputStream out =NewObjectOutputStream (BUF); to + out.writeobject (user); - the Out.close (); * //creates an object input stream that reads objects from the input stream through the ReadObject () of the object input stream $ObjectInputStream in =NewObjectInputStream (NewBytearrayinputstream (Buf.tobytearray ())); Panax Notoginseng -user =(User) in.readobject (); the +System.out.println ("After serialization:" +user); A the In.close (); + } - } $ $ before serialization:weidong123456 -After Serialization:weidongnull
Java-Object Serialization Code instance