所以最近我一直在努力使用 Libgdx 的序列化工具。我目前正在尝试将我的播放器类和我的 GameEntry 类写入一个文件,以便稍后在用户退出应用程序时访问该文件。我目前的方法在我的应用程序的计算机版本上运行良好,但在 android 平台上,它并没有取得同样的成功。我已添加到清单中,但仍然出现以下错误。
com.badlogic.gdx.utils.GdxRuntimeException: Error writing file: player.dat (Absolute)
然后发生以下错误,导致游戏崩溃。
com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: scores.dat (Absolute)
这是游戏这一部分的代码。根据平台是否检测到这些文件,我在 create() 方法中调用了 save 和 read 方法。
public static void saveFile(ArrayList<GameEntry> scores) throws IOException{
FileHandle file = Gdx.files.absolute("scores.dat");
OutputStream out = null;
try{
file.writeBytes((serialize(scores)), false);
}catch(Exception ex){
}finally{
if(out != null) try{out.close();} catch(Exception ex){}
}
Gdx.app.log(Asteroids.LOG, "Saving File: " + scores.toString());
}
public static void savePlayer(Player player) throws IOException{
FileHandle file = Gdx.files.absolute("player.dat");
PlayerData playerData = new PlayerData(player);
OutputStream out = null;
try{
file.writeBytes((serialize(playerData)), false);
}catch(Exception ex){
Gdx.app.log(Asteroids.LOG, ex.toString());
}finally{
if(out != null) try{out.close();} catch(Exception ex){}
}
Gdx.app.log(Asteroids.LOG, "Saving Player");
}
@SuppressWarnings("unchecked")
public static ArrayList<GameEntry> readFile() throws IOException, ClassNotFoundException{
FileHandle file = Gdx.files.absolute("scores.dat");
scores = (ArrayList<GameEntry>) deserialize(file.readBytes());
Gdx.app.log(Asteroids.LOG, "Reading File: " + scores.toString());
return scores;
}
public static Player readPlayer() throws IOException, ClassNotFoundException{
Player player = null;
PlayerData playerData = null;
FileHandle file = Gdx.files.absolute("player.dat");
playerData = (PlayerData) deserialize(file.readBytes());
player = new Player(new Texture(Gdx.files.internal("Ships/defaultShip.png")), new Vector2((Gdx.graphics.getWidth() / 2) - 25, 50), Player.PLAYER_WIDTH,Player.PLAYER_HEIGHT);
player.setHealth((int) playerData.getPlayerHealth());
player.setMaxHealth((int) playerData.getPlayerMaxHealth());
player.setShieldHealth(playerData.getPlayerShieldHealth());
player.setBulletCount(playerData.getBulletCount());
player.setShieldRegenRate(playerData.getPlayerShieldRegenRate());
player.setPlayerScore(playerData.getPlayerScore());
player.setEntityTexture(new Texture(Gdx.files.internal(playerData.getPlayerShipName())));
player.update();
Gdx.app.log(Asteroids.LOG, "Reading Player");
return player;
}
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
任何帮助或意见将不胜感激。