gpt4 book ai didi

java - Java 中的序列化和反序列化

转载 作者:行者123 更新时间:2023-12-02 07:33:00 25 4
gpt4 key购买 nike

我刚刚关注了 Tutorial对于序列化,我想知道为什么它不起作用。我有一个这样的游戏类:

import java.io.Serializable;

public class Game implements Serializable{

private static final long serialVersionUID = -4795536311274486893L;
protected int SHOT_SPEED;
protected int PLAYER_SPEED;
Player player;
ArrayList<SpaceObject> objects;
int level, score;
Dimension resolution;
and so on...

我的阅读器方法应该处理对象 IO,如下所示:

public boolean saveGame(Game game) {
try {
FileOutputStream fileOut = new FileOutputStream(defaultDataName+".ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(game);

out.close();
fileOut.close();
return true;
}
catch (IOException i) {
return false;
}

}

public Game loadGame() throws IOException {
if (readRawData(defaultDataName) == "") throw new IOException("Data was deleted");
Game game = null;
try {
FileInputStream fileIn = new FileInputStream(defaultDataName+".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);

game = (Game) in.readObject();

in.close();
fileIn.close();
}
catch (ClassNotFoundException e) {
throw new IOException("Class not Found: " + e.getMessage());
}
return game;
}

在我看来,我所做的一切都与教程中的完全一样,所以为什么它不起作用。 (它抛出一个 ClassNotFoundError。感谢您的帮助!

最佳答案

运行第二个方法时,该类似乎不在您的类路径中。

  • 您能否发布完整的异常消息?
  • 您是否使用具有相同类路径的序列化和反序列化器?

关于java - Java 中的序列化和反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com