Public classObjectsaver { Public Static voidMain (string[] args)throwsException {/*where the d:\\objectfile.obj represents the file that holds the serialized object*/ //Serializing ObjectsObjectOutputStream out =NewObjectOutputStream (NewFileOutputStream ("C:\\test\\objectfile.obj")); Customer Customer=NewCustomer ("Pock", 24); Out.writeobject ("Hello!");//write literal literals constantOut.writeobject (NewDate ());//Write anonymous Date objectOut.writeobject (customer);//write to the Customer objectOut.close (); //deserializing ObjectsObjectInputStream in =NewObjectInputStream (NewFileInputStream ("C:\\test\\objectfile.obj")); System.out.println ("Obj1" + (String) in.readobject ());//read literal constantsSystem.out.println ("Obj2" + (Date) in.readobject ());//Read Anonymous Date objectCustomer OBJ3 = (customer) in.readobject ();//read the Customer objectSystem.out.println ("Obj3" +obj3); In.close (); }}classCustomerImplementsSerializable {PrivateString name; Private intAge ; PublicCustomer (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicString toString () {return"Name=" + name + ", age=" +Age ; }}
Serialization and deserialization of files in Java