Java对象的序列化和反序列化

对象的序列化:将对象转换成字节序列,并可以写入文件,保存到硬盘上,ObjectOutputStream类。

对象反序列化:从文件中读取字节流,并转换成对象。ObjectInputStream类。

package com.example.javatest;

/**
 * Author:W
 * 玩家类对象可序列化,则需要实现接口Serializable
 */
public class Player implements java.io.Serializable{
    public  String name;
    public  int id;
    public  int age;
    //如果有一个属性不是可序列化的,则该属性必须注明是短暂的。
    public  transient String tempLoginTime;

}
package com.example.javatest;//包名定义

/**
 * Author:W
 * 对象序列化与反序列化
 * 1)序列化:ObjectOutputStream
 * 2)反序列化:ObjectInputStream
 */
import java.io.*;

public class MainTest{

    public static void main(String[] args)
    {
        String  path = "G:/JavaTest/LocalFiles/Test/player.ser";

        System.out.println("====Player类对象序列化====");
        Player  player = new Player();
        player.id = 10023;
        player.name = "C罗";
        player.age = 34;
        player.tempLoginTime ="2021-08-15";

        try
        {
            FileOutputStream  fileOutputStream = new FileOutputStream(path);
            ObjectOutputStream objOut = new ObjectOutputStream(fileOutputStream);
            objOut.writeObject(player);
            objOut.close();
            fileOutputStream.close();

            System.out.println("Player对象序列化完成!路径:"+ path);
        }catch(IOException e)
        {
            e.printStackTrace();
        }


        System.out.println("====Player类反序列化====");
        Player player2 = null;
        try
        {
            FileInputStream fileInputStream = new FileInputStream(path);
            ObjectInputStream objInput = new ObjectInputStream(fileInputStream);
            player2 = (Player)objInput.readObject();

            objInput.close();
            fileInputStream.close();
        }catch (IOException e)
        {
            e.printStackTrace();
            return;
        }catch(ClassNotFoundException e)
        {
            System.out.println("Class类不存在!");
            e.printStackTrace();
            return;
        }

        System.out.println("id = "+player2.id);
        System.out.println("name = "+player2.name);
        System.out.println("age = "+player2.age);
        System.out.println("tempLoginTime = "+player2.tempLoginTime);
    }

}

运行结果如下:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Data菌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值