使用ObjectOutputStream保存HashMap [英] HashMap saving with ObjectOutputStream

查看:263
本文介绍了使用ObjectOutputStream保存HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在命令上保存远距传送点,我有一个 HashMap

To save teleportation points on command, I have an HashMap:

public HashMap<Player, Location> mapHomes = new HashMap<>();

按以下方式访问哪个:

if(cmd.getName().equalsIgnoreCase("sethome")){
    Location loc = player.getLocation();
    mapHomes.put(player, loc);
    sender.sendMessage("Home set !");
    return true;
}
if(cmd.getName().equalsIgnoreCase("home")){
    Location loc1 = mapHomes.get(player);
    player.teleport(loc1);
    sender.sendMessage("Teleported to home");
    return true;
}
return false;

由于这些设置应在重新启动时保留,因此我实现了一个保存方法:

Since these settings should be kept on restart, I've implemented a save method:

public void save(HashMap<Player,Location> mapHome, String path) throws NotSerializableException{
    try{
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
        oos.writeObject(mapHome);
        oos.flush();
        oos.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}

但是它不起作用。它抛出 NotSerializableException

But it's not working. It throws NotSerializableException.

我认为主要问题是 Player Location 不是可序列化的类型,那么我应该怎么写这个 HashMap

I think the main problem is Player and Location are not serializable types, so what should I do to write this HashMap?

推荐答案

HashMap 已经可以可序列化

问题是地图内的对象不是,因此您也必须使它们可序列化。

The problem is that the objects inside the map are not, so you'll have to make them serializable, too.

public class SerializedPlayer extends Player implements Serializable {
    public SerializedPlayer() {}
    public SerializedPlayer(Player playerToClone) {
        this.setField1(playerToClone.getField1());
        // Set all the fields
    }
}

何时添加到地图中:

map.put(new SerializedPlayer(player), new SerializedLocation(location));

这篇关于使用ObjectOutputStream保存HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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