序列化与解序列化

《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

 

posted @ 2017-05-23 15:20  CYTing  阅读(382)  评论(1编辑  收藏  举报