对象序列化
何为对象序列化
对象序列化:就是将对象保存到磁盘中,或者在网络中传输对象
当序列化运行时检测到类中的以下问题之一时抛出。
1.类的串行版本与从流中读取的类描述符的类型不匹配
2.该类包含未知的数据类型
3.该类没有可以访问的无参数构造函数
如果出问题了,如何解决
给对象所属的类加一个值:private static final long serialVersionUI=42L
;
如果一个对象的属性不想被序列化?
用transient
修饰这个属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package 流.对象序列化;
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;
public class ObjectStreamDemo {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { // TODO Auto-generated method stub //对象序列化 ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:\\text.txt")); Student s=new Student("张三",11); oos.writeObject(s); oos.close(); //对象反序列化 ObjectInputStream ooi=new ObjectInputStream(new FileInputStream("D:\\text.txt")); Student s1=(Student)ooi.readObject(); System.out.println(s1.getName()+s1.getAge()); }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package 流.对象序列化;
import java.io.Serializable;
public class Student implements Serializable{ private static final long serialVersionUID=42L;//修改对象所属类,如何解决 private String name; private transient int age;//如果这个属性不想被序列化 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student() { super(); // TODO Auto-generated constructor stub } public Student(String name, int age) { super(); this.name = name; this.age = age; }
}
|