Java 序列化与反序列化

若要类能被序列化要实现serializable借口。

我自己理解的序列化与反序列化:

序列化:将对象的值写入Txt或者ser文件当中,对象可以以文本的方式进行存储。写入后对象为空。

反序列化:将Txt文件或者ser文件读取,将其值按照对应关系赋给对象。

其中student类在另一文件中定义,定义如下:

String id;
    String name;
    String score;

void set(String id,String name,String score){
        this.id=id;
        this.name=name;
        this.score=score;
    }

代码:

package home;

import java.io.*;

public class Xuliehua {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student one=new Student();
        one.set("141114101","dupangzi","11");
        Student two=new Student();
        two.set("141114102","jiangshouzi","99");//innitialize object
        try(ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("D://1.ser"))){
            os.writeObject(one);
            os.writeObject(two);
            System.out.println("job done!");
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

}

此时1.ser文件增加两行内容


2.反序列化

反序列化:从foo.ser 里面读出对象,通过强制类型转化为student类

package home;

import java.io.*;

public class ReadSer {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try ( final ObjectInputStream is = new ObjectInputStream(new FileInputStream("D://foo.ser"))) {
            while (true)
            {
                Student oneStu=(Student)is.readObject();
                Student twoStu=(Student)is.readObject();
                System.out.println(oneStu.id + " " + oneStu.name + " "+ oneStu.score);
                System.out.println(twoStu.id + " " + twoStu.name + " "+ twoStu.score);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值