PackageIoliu;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream; Public classObjectinputstreamtest { Public Static voidMain (string[] args) {File file=NULL; FileInputStream FIS=NULL; ObjectInputStream Ois=NULL; User User=NULL; FileOutputStream Fos=NULL; ObjectOutputStream Oos=NULL; Try { //saving object data to memoryFile =NewFile ("D:\\2017.txt"); FOS=Newfileoutputstream (file); Oos=NewObjectOutputStream (FOS); User=NewUser ("Rose", "[email protected]", "170"); Oos.writeobject (user); //getting object data from memoryFIS =Newfileinputstream (file); Ois=NewObjectInputStream (FIS); Try{User user1=(User) ois.readobject (); System.out.println (User1.getname ()+ "" "+user1.getage () +" "+user1.getmail () +" "+user.getheight ()); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }finally{ Try{Oos.flush (); Oos.close (); Ois.close (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }}
PackageIoliu;Importjava.io.Serializable;//add Interface object serialization implements Public classUserImplementsserializable{PrivateString name; Private intAge ; PrivateString Mail; PrivateString height; PublicUser () {Super(); } PublicUser (String name,intAge , string mail, string height) { Super(); This. Name =name; This. Age =Age ; This. Mail =Mail; This. Height =height; } PublicString Getmail () {returnMail; } Public voidSetmail (String mail) { This. Mail =Mail; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicString getheight () {returnheight; } Public voidsetheight (String height) { This. Height =height; }}
Objectinputstreamtest object type input and output stream