• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

java 序列化与反序列化例子

java wangting 3年前 (2017-10-18) 417次浏览
import java.io.*;

/**
 * Created by wangting1 on 2017/9/20.
 */
public class Test implements Serializable {

    private static final long serialVersionUID = 1L;
    private String name="SheepMu";
    private int age=24;
    Test(){

    }

    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 static void main(String[] args)
    {//以下代码实现序列化
        try
        {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/wangt/wtdata0/temp/my.txt"));//输出流保存的文件名为 my.out ;ObjectOutputStream能把Object输出成Byte流
            Test myTest=new Test();
            myTest.setName("testname");
            oos.writeObject(myTest);
            oos.flush();  //缓冲流
            oos.close(); //关闭流
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        Test t = new Test();
        t.fan();//调用下面的  反序列化  代码
    }
    public static void fan()//反序列的过程
    {
        ObjectInputStream oin = null;//局部变量必须要初始化
        try
        {
            oin = new ObjectInputStream(new FileInputStream("/Users/wangt/wtdata0/temp/my.txt"));
        } catch (FileNotFoundException e1)
        {
            e1.printStackTrace();
        } catch (IOException e1)
        {
            e1.printStackTrace();
        }
        Test mts = null;
        try {
            mts = (Test ) oin.readObject();//由Object对象向下转型为MyTest对象

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("name="+mts.name);
        System.out.println("age="+mts.age);
    }


}

喜欢 (0)