码迷,mamicode.com
首页 > 其他好文 > 详细

序列化与反序列化

时间:2016-05-29 21:37:43      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

package com.wzy.main;

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

@SuppressWarnings("serial")
class Person implements Serializable{
    public Person(String name,Integer id,Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    private String name;
    private Integer id;
    private transient Integer age;//transient属性不会被序列化
    @Override
    public String toString() {
        return "name:"+name+", id:"+id+", age:"+age;
    }
}

public class Test02 {
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        /**
         * 需要被序列化的对象继承Serializable接口,表明此对象可以被序列化
         * 序列化,将一个对象以二进制的形式保存到磁盘上
         * 反序列化,从磁盘上读取文件返回此对象
         * */
        ser(new Person("tom",10001,45));//序列化
        dser();//反序列化
    }
    static void ser(Person p) throws FileNotFoundException, IOException{
        ObjectOutputStream out = new ObjectOutputStream(
                new FileOutputStream("E:"+File.separator+"person"));
        out.writeObject(p);
        out.close();
        System.out.println("对象已被保存到本地");
        
    }
    static void dser() throws FileNotFoundException, IOException, ClassNotFoundException{
        ObjectInputStream in = new ObjectInputStream(
                new FileInputStream("E:"+File.separator+"person"));
        Person p = (Person)in.readObject();
        in.close();
        System.out.println(p.toString());
    }
}

 

序列化与反序列化

标签:

原文地址:http://www.cnblogs.com/wwzyy/p/5540253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!