对象的序列化和反序列化
1.对象的序列化,就是将Object转换成byte序列,反之叫对象的反序列化:
序列化流(ObjectOutputStream),是过滤流
反序列化流(ObjectInputStream),readObject
序列化接口(Serializable),对象必须实现序列化接口,才能进行序列化,否则将出现异常
这个接口没有任何方法,只是一个标准
将Java对象保存起来需要将对象序列化,保存成字节,在网络中传输对象也需要转换成字节序列;
加了transient修饰的属性不会进行JVM默认的序列化,也可以自己完成这个元素的序列化
package com.wxd.test3; import java.io.Serializable; public class Student implements Serializable{ private String stuno; private String stuname; private transient int stuage;//该元素不会进行JVM默认的序列化 public Student() { } public Student(String stuno, String stuname, int stuage) { this.stuno = stuno; this.stuname = stuname; this.stuage = stuage; } public String getStuno() { return stuno; } public void setStuno(String stuno) { this.stuno = stuno; } public String getStuname() { return stuname; } public void setStuname(String stuname) { this.stuname = stuname; } public int getStuage() { return stuage; } public void setStuage(int stuage) { this.stuage = stuage; } @Override public String toString() { return "Student{" + "stuno='" + stuno + '\'' + ", stuname='" + stuname + '\'' + ", stuage=" + stuage + '}'; } }
package com.wxd.test3; import java.io.*; public class ObjectSerializable { public static void main(String[] args) throws Exception { String file="demo\\obj.dat"; //1.对象的序列化 /*ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file)); Student stu=new Student("00001","mike",20); oos.writeObject(stu); oos.flush(); oos.close();*/ //2.对象的反序列化将对象从文件里面读出来 ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file)); Student stu=(Student)ois.readObject(); System.out.println(stu); ois.close(); } }

浙公网安备 33010602011771号