java序列化

1、基本概念
序列化:把内存对象转换为字节码的过程
反序列化:把字节码转换为内存对象的过程
2、实例

实体类:

import java.io.Serializable;

public class Animal implements Serializable{
    private static final long serialVersionUID = -5809782578272943999L;
    private String saySome;
    private String name;
    private String sex;
    private int years;
    public String getSaySome() {
        return saySome;
    }

    public void setSaySome(String saySome) {
        this.saySome = saySome;
    }
    public void say(){
        System.out.println("你说啥:"+saySome);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getYears() {
        return years;
    }

    public void setYears(int years) {
        this.years = years;
    }
}
package com.test;

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;

public class TestSerial {
    //序列化
    public static void serialize(Animal animal)throws FileNotFoundException,IOException{
        ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(new File("E:/Animal.txt")));
        oo.writeObject(animal);
        System.out.println("Animal对象序列化成功!");
        oo.close();
    }
    //反序列化
    public static void unserialize()throws FileNotFoundException,IOException, ClassNotFoundException{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("E:/Animal.txt")));
        Animal animal = (Animal) ois.readObject();
        System.out.println("Person对象反序列化成功!");
        System.out.println("动物名称:"+animal.getName()+"\n动物性别:"+animal.getSex()+"\n动物年龄:"+animal.getYears());
    }
    public static void main(String[] args) throws Exception {
        Animal animal=new Animal();
        animal.setName("狗");
        animal.setSex("男");
        animal.setYears(10);
        serialize(animal);
        unserialize();
    }
}

3、注意问题

  1. 必须实现Serializable接口或Externalizable接口
  2. 必须要有serialVersionUID
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值