Java 序列化

来源:互联网 发布:传感器融合算法 编辑:程序博客网 时间:2024/05/19 07:26
/* 对象序列化没有方法的接口通常称为"标记接口",只要写上实现该接口,即表明拥有了标记,以形成某个特定的作用.序列化只能针对堆内存了的对象及成员,比如被静态修饰的成员在方法区里,不能被序列化.又,如果对于非静态的成员你也想使其;不被序列化,就应该用transient修饰.*/import java.io.*;class  Person implements Serializable{//public static final long serialVersionUID = 42L;① String name;//private String name;//如果①处被使用,这里就不会出问题,也就是说,每个对象的序列号唯一由对象成员所决定,当类成员发生改变时,如果.class文件和被序列化的对象不匹配,就会导致出错.int age;public Person(String name,int age){this.name=name;this.age=age;}public String toString(){return "name="+name+", age="+age;}}public class  SerializableDemo{public static void main(String[] args) throws IOException,ClassNotFoundException{//readObj();writeObj();}public static void readObj() throws IOException,ClassNotFoundException{ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.txt"));for(int i=0;i<2;i++){Person p=(Person)ois.readObject();System.out.println(p);}ois.close();}public static void writeObj() throws IOException{ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("obj.txt"));oos.writeObject(new Person("lisi",23));oos.writeObject(new Person("zhangsan",245));oos.close();}}

原创粉丝点击