java 对象输入输出流读写文件的操作实例
java对象输入输出流读写文件的操作实例
java支持对对象的读写操作,所操作的对象必须实现Serializable接口。
实例代码:
packagevo; importjava.io.Serializable; publicclassAnimalimplementsSerializable{ privatestaticfinallongserialVersionUID=1L; privateStringname; privateIntegerweight; privateStringcolor; privateStringtype; privateIntegerage; privateIntegerlifetime; publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicIntegergetWeight(){ returnweight; } publicvoidsetWeight(Integerweight){ this.weight=weight; } publicStringgetColor(){ returncolor; } publicvoidsetColor(Stringcolor){ this.color=color; } publicStringgetType(){ returntype; } publicvoidsetType(Stringtype){ this.type=type; } publicIntegergetAge(){ returnage; } publicvoidsetAge(Integerage){ this.age=age; } publicIntegergetLifetime(){ returnlifetime; } publicvoidsetLifetime(Integerlifetime){ this.lifetime=lifetime; } publicAnimal(Stringname,Integerweight,Stringcolor,Stringtype,Integerage,Integerlifetime){ super(); this.name=name; this.weight=weight; this.color=color; this.type=type; this.age=age; this.lifetime=lifetime; } @Override publicStringtoString(){ return"Animal[name="+name+",weight="+weight+",color="+color+",type="+type+",age="+age+",lifetime="+lifetime+"]"; } }
packageobjectstream; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileOutputStream; importjava.io.ObjectInputStream; importjava.io.ObjectOutputStream; importvo.Animal; publicclassTestObjectStream{ publicstaticvoidmain(String[]args){ try{ ObjectOutputStreamoos=newObjectOutputStream(newFileOutputStream(newFile("d:/oos.dat"))); Animala1=newAnimal("tiger",120,"red","cat",12,20); Animala2=newAnimal("eagle",10,"gold","bird",6,10); oos.writeObject(a1); oos.writeObject(a2); oos.flush(); oos.close(); ObjectInputStreamois=newObjectInputStream(newFileInputStream("d:/oos.dat")); Animalra1=(Animal)ois.readObject(); System.out.println(ra1.toString()); Animalra2=(Animal)ois.readObject(); System.out.println(ra2.toString()); }catch(Exceptione){ e.printStackTrace(); } } }
输出结果:
Animal[name=tiger,weight=120,color=red,type=cat,age=12,lifetime=20] Animal[name=eagle,weight=10,color=gold,type=bird,age=6,lifetime=10]
如有疑问请留言或者到本站社区交流讨论,本站关于java开发的文章还有很多,希望大家搜索查阅,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!