序列化Java中的多个不同对象 [英] Serialize multiple different objects single in Java

查看:67
本文介绍了序列化Java中的多个不同对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会尝试用困难的方式做到这一点,所以请告诉我是否有更好的解决方案.

I might be trying to do this the hard way so let me know if there is a better solution.

我正在用Java开发一个简单的文字游戏,您可以通过GUI选择动作.我有几个班级正在尝试序列化一个是播放器,另一个是NPC.是否有一种简单的方法可以将一个以上的对象(播放器和NPC)序列化到同一文件中?我可以序列化一个对象并将其重新加载到游戏中.

I am making a simple text game in Java which you select your actions by a GUI. I have a couple of classes I am trying to serialize one being the player and another being an NPC. Is there an easy way to serialize more then one object (player and NPC) into the same file? I can serialize one object and load it back into the game.

我会以错误的方式处理吗?有没有更简单的方法来尝试保存游戏状态?

Am I going about this the wrong way? Is there a simpler way of trying to save the game state?

如果我有一个创建多个对象的类,并且我对该类进行了序列化,那么它创建的对象也将被序列化吗?

If I have a class that creates multiple objects and I serialize that class, will the objects it created be serialized as well?

谢谢

推荐答案

顺序写入对象的另一种方法是将它们存储在集合(例如HashMap)中,因为可以序列化集合.这可能会使检索时的管理起来更容易一些,尤其是当您有许多要序列化/反序列化的对象时.以下代码演示了这一点:

An alternate approach to writing objects sequentially is to store them in a collection (e.g. a HashMap), since collections can be serialized. This may make it a little easier to manage upon retrieval, especially if you have many objects to serialize/deserialize. The following code demonstrates this:

    String first = "first";
    String second = "second";
    HashMap<String, Object> saved = new HashMap<String, Object>();
    saved.put("A", first);
    saved.put("B", second);

    try {
        FileOutputStream fos = new FileOutputStream("test.obj");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(saved);
        oos.flush();
        oos.close();
        fos.close();


        FileInputStream fis = new FileInputStream("test.obj");
        ObjectInputStream ois = new ObjectInputStream(fis);

        HashMap<String,Object> retreived = (HashMap<String,Object>)ois.readObject();
        fis.close();

        System.out.println(retreived.get("A"));
        System.out.println(retreived.get("B"));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

运行此操作将导致:

first
second

这篇关于序列化Java中的多个不同对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆