21st Day -01-io Stream (serialization of objects)
ObjectInputStream and ObjectOutputStream
- The object being manipulated needs to implement the Serializable interface (tag interface)
- Not required, but it is strongly recommended that all serializable classes be explicitly declared Serialversionuid
PackageBxD;ImportJava.io.*; Public classObjectstreamdemo { Public Static voidReadobj ()throwsException {objectinputstream ois=NewObjectInputStream (NewFileInputStream ("Person.object")); Person Person=(person) ois.readobject (); SYSTEM.OUT.PRINTLN (person); Ois.close (); } Public Static voidWriteobj ()throwsException {objectoutputstream oos=NewObjectOutputStream (NewFileOutputStream ("Person.object")); Oos.writeobject (NewPerson ("Lily", "the", "Us")); Oos.close (); } Public Static voidMain (string[] args)throwsException {//writeobj ();readobj (); }}/*The output is LILY:0:CN because age is not serialized (using the initial value of 0), and the static variable country is not serialized (using the initial value of CN).*/classPersonImplementsSerializable { Public Static Final LongSerialversionuid = 42L;//It is strongly recommended that all serializable classes be explicitly declared Serialversionuid PrivateString name; transient intAge//If an instance variable does not need to be serialized, you can use the transient adornment StaticString country = "cn";//the serialization behavior is only for the Java heap (heap), and static variables do not exist in the heap.Person (String name,intAge , String Country) { This. Name =name; This. Age =Age ; This. Country =Country; } PublicString toString () {returnName + ":" + Age + ":" +Country; }}
Bi Xiangdong _java Basic Video tutorial 21st day _io Stream (1)