java对像序列化

package cn.stat.p2.demo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class objectdemo {

    /**
     * @param args
     * @throws IOException 
     * @throws FileNotFoundException 
     * @throws ClassNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
        readObject();
        //writeObject();

    }

    private static void readObject() throws FileNotFoundException, IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.txt"));
        Preson p=(Preson)ois.readObject();
        System.out.print(p.getName()+":"+p.getAge());
        ois.close();
        
    }

    public static void writeObject() throws IOException, FileNotFoundException {
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("obj.txt"));
        //序列化的对像,一定要实现Serializable接口
        oos.writeObject(new Preson("小王",12));
        oos.close();
    }

}

 

package cn.stat.p2.demo;

import java.io.Serializable;

public class Preson implements Serializable {
    
    
    //序列化运行时使用一个称为 serialVersionUID 的版本号与每个可序列化类相关联,
    //该序列号在反序列化过程中用于验证序列化对象的发送者和接收者是否为该对象加载了与序列化兼容的类。
    //如果接收者加载的该对象的类的 serialVersionUID 与对应的发送者的类的版本号不同,
    //则反序列化将会导致 InvalidClassException。可序列化类可以通过声明名为 "serialVersionUID" 的字段
    //(该字段必须是静态 (static)、最终 (final) 的 long 型字段)显式声明其自己的 serialVersionUID:

    private static final long serialVersionUID = 42213123123L;

    
    
    private String name;
    private 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 Preson(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    

}

 

posted @ 2015-09-04 21:10  自由无风  阅读(247)  评论(0编辑  收藏  举报