保存和恢复数据的问题
问题描述:
我退出活动时保存了一些内容。 首先在一个对象中,第二个是一个int值。保存和恢复数据的问题
它可以保存,但是当我尝试读回时,在尝试获取第二个项目时出现EOFException。
private void saveData(){
FileOutputStream saveFile = null;
try {
saveFile = this.openFileOutput(STATE_SAVE_FILE_NAME, Context.MODE_PRIVATE);
ObjectOutput output = new ObjectOutputStream(saveFile);
output.writeObject(game);
output.write(ScoringForScoreloop.getScore());
output.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
try {
saveFile.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
private void restoreData(){
FileInputStream restoreFile = null;
try {
try {
restoreFile = this.openFileInput(STATE_SAVE_FILE_NAME);
}
catch (FileNotFoundException e) {
inGame = false;
return; // If no file then ok - we will start a new game
}
ObjectInput input = new ObjectInputStream(restoreFile);
game = (GameControl) input.readObject();
ScoringForScoreloop.setScore(input.readInt());
inGame = (game!=null);
} catch (Exception e) {
inGame = false;
return; // If error then we will start a new game
}
finally {
try {
restoreFile.close();
this.deleteFile(STATE_SAVE_FILE_NAME); // delete it so we don't restore from it again
}
catch (Exception ex) {
inGame = false;
return; // If error then we will start a new game
}
}
}
答
我从来没有在Java中使用这些类,但我会冒险猜测。我怀疑这个问题是Java中的int和Integer之间的区别。
在写代码,你有没有试着用
output.writeInt(ScoringForScoreloop.getScore());
这样,你应该是读对称和类型处理方面写更换
output.write(ScoringForScoreloop.getScore());
。
完美!非常感谢。 – theblitz 2011-06-09 22:58:11