Java IO流对象的序列化和反序列化实例详解
Java—IO流对象的序列化和反序列化
序列化的基本操作
1.对象序列化,就是将Object转换成byte序列,反之叫对象的反序列化。
2.序列化流(ObjectOutputStream),writeObject方法用于将对象写入输出流中;
反序列化流(ObjectInputStream),readObject方法用于从输入流中读取对象。
3.序列化接口(Serializeable)
对象必须实现序列化接口,才能进行序列化,否则会出现异常。这个接口没有任何方法,只是一个标准。
packagecom.test.io; importjava.io.FileInputStream; importjava.io.FileOutputStream;importjava.io.ObjectInputStream; importjava.io.ObjectOutputStream; publicclassObjectSerialzeTest{ /** *对象的序列化 *@paramfile *@throwsException */ publicvoidObjectOutput(Stringfile)throwsException{ ObjectOutputStreamoos=newObjectOutputStream(newFileOutputStream(file)); Studentstu=newStudent("002","张四",12); oos.writeObject(stu); oos.flush(); oos.close(); } /** *对象的反序列化 *@paramfile *@throwsException */ publicvoidObjectInput(Stringfile)throwsException{ ObjectInputStreamois=newObjectInputStream(newFileInputStream(file)); Studentstu=(Student)ois.readObject(); System.out.println(stu.toString()); ois.close(); } publicstaticvoidmain(String[]args)throwsException{ Stringfile="F:\\javaio\\obj.dat"; ObjectSerialzeTestost=newObjectSerialzeTest(); ost.ObjectOutput(file); ost.ObjectInput(file); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!