• 序列化与解序列化


    《Head First Java》

    1.概念:序列化(Serialization):把对象转换为字节序列的过程。

               解序列化(Deserilization):把字节序列恢复为对象的过程。

    2.用于:在程序运行结束后,可把对象序列化后永久地保存在硬盘上。

               在网络上传送对象的字节序列。

    3.对象序列化的步骤:

    (1).创建FileOutputStream(创建存取文件的FileOutputStream对象,如果文件不存在,它会自动被创建出来)

         FileOutputStream fileStream=new FileOutputStream("MyGame.ser");

    (2).创建ObjectOutputStream(它能让你写入对象,但无法直接地连接文件,所以需要参数的指引)

         ObjectOutputStream os=new ObjectOutputStream(fileStream);

    (3).写入对象(将变量所引用的对象序列化并写入MyGame.ser这个文件)

         os.writeObject(characterOne);
         os.writeObject(characterTwo);
         os.writeObject(characterThree);

    (4).关闭ObjectOutputStream(关闭所关联的输出串流)

         os.close();

    即:Object 写入 ObjectOutputStream 连接到 FileOutputStream 到文件

    3.解序列化的步骤:还原对象

    (1).创建FileInputStream(如果文件不存在就会抛出异常)

         FileInputStream fileStream=new FileInputStream("MyGame.ser");

    (2).创建ObjectInputStream(它知道如何读取对象,但是要链接的stream提供文件存取)

         ObjectInputStream os=new ObjectInputStream(fileStream);

    (3).读取对象(每次调用readObject方法都会从stream中读出下一个对象,读取顺序与写入顺序相同,次数超过会抛出异常)

         Object one=os.readObject();
         Object two=os.readObject();
         Object three=os.readObject();

    (4).转换对象类型(返回值是Object类型,因此必须转换类型)

         GameCharacter elf=(GameCharacter)one;
         GameCharacter troll=(GameCharacter)two;
         GameCharacter magician=(GameCharacter)three;

    (5).关闭ObjectInputStream(FileInputStream会自动跟着关掉)

         os.close();

    即:文件 被读取 FileInputStream 被连接 ObjectInputSteam 恢复成对象

    4.一个例子

    import java.io.*;
    //存储与恢复游戏人物
    public class GameSaverTest{
        
        public static class GameCharacter implements Serializable//测试序列化的类
        {
            int power;
            String type;
            String[] weapons;
            
            public GameCharacter(int p, String t, String[] w)
            {
                power = p;
                type = t;
                weapons = w;
            }
            
            public int getPower() {
                return power;
            }
            
            public String getType() {
                return type;
            }
            
            public String getWeapons() {
                String weaponList = "";
                for (int i = 0; i < weapons.length; i++)
                {
                    weaponList += weapons[i] + " ";
                }
                return weaponList;
            }
        }
        
        public static void main (String[] args) {
            //创建人物
            GameCharacter one = new GameCharacter(50, "Elf", new String[] {"bow", "sword", "dust"});
            GameCharacter two = new GameCharacter(200, "Troll", new String[] {"bare hands", "big axe"});
            GameCharacter three = new GameCharacter(120, "Magician", new String[] {"spells", "invisibility"});
            //假设此处有改变人物状态值的程序代码
            try {
                ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Game.ser"));
                os.writeObject(one);
                os.writeObject(two);
                os.writeObject(three);
                os.close();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }
            
            one = null;
            two = null;
            three = null;//设定成null,因此无法存取堆上的这些对象
            
            try {//再从文件中把对象读取回来
                ObjectInputStream is = new ObjectInputStream(new FileInputStream("Game.ser"));
                GameCharacter oneRestore = (GameCharacter) is.readObject();
                GameCharacter twoRestore = (GameCharacter) is.readObject();
                GameCharacter threeRestore = (GameCharacter) is.readObject();
                //看看是否成功
                System.out.println("One's type: " + oneRestore.getType());
                System.out.println("Two's type: " + twoRestore.getType());
                System.out.println("Three's type: " + threeRestore.getType());
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    结果为:

    One's type: Elf
    Two's type: Troll
    Three's type: Magician

  • 相关阅读:
    【转】差分进化算法(DE)
    Cocos Creator 小游戏之找财神(上)
    浅析java线程池
    docker rocketMQ 详细 三分钟搞定 面试有这篇就够了
    docker nacos2.03 详细流程 5分钟搞定
    springboot+rocketmq 快速入门面试篇
    nacos集群 docker 有这一篇就够了,详细
    Ubuntu vi 命令使用详细说明
    idea实现json转JavaBean, 还得是fastjson
    docker nacos2.0.3 SQL语句
  • 原文地址:https://www.cnblogs.com/dengyt/p/6894247.html
Copyright © 2020-2023  润新知