Java 读取文件时出现NullPointerException
当我加载这个文件时,我总是得到NullPointerException。我尝试了很多东西,但我找不到解决它的方法。当我保存时,我使用了游戏对象Java 读取文件时出现NullPointerException,java,Java,当我加载这个文件时,我总是得到NullPointerException。我尝试了很多东西,但我找不到解决它的方法。当我保存时,我使用了游戏对象 @Override public void load(Superhero aHero,Villain aVillain) throws IOException, ClassNotFoundException { ObjectInputStream ois = null; FileInputStr
@Override
public void load(Superhero aHero,Villain aVillain) throws IOException, ClassNotFoundException {
ObjectInputStream ois = null;
FileInputStream fis = null;
File f = new File("C:\\prog24178\\dcgames.dat");
Game aGame = new Game(aHero,aVillain);
try {
fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
while(true){
aGame = (Game) ois.readObject();
System.out.println(aGame);
}
} catch(EOFException eof){
ois.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(DcGameController.class.getName()).log(Level.SEVERE, null, ex);
}
}
当我打开文件时,我会看到类似的内容:
’ sr
model.Game ^r Z gameOverZ heroTurnL theHerot Lmodel/Superhero;L
theVillaint Lmodel/Villain;xp sr model.hero.Batman ^r Z armedL sidekickq ~ xr model.Superhero ^r I energyZ secretIdentityL codenamet Ljava/lang/String;L hometownq ~ xr model.Avatar ^r
I agilityI enduranceI fightingI hitPointsI intuitionI psycheI reasonI strengthL firstNameq ~ L lastNameq ~ xp W t q ~ t Batmant Gotham Citysq ~ t Dickt Grayson ppsr model.villain.Cheetah ^r xr
model.Villain ^r I energyZ insaneL codenameq ~ xq ~ b t Priscillat Rich t Cheetah
所以我知道它工作,但我想阅读,然后我可以设置我需要使用的设置
这是我的保存方法:
@Override
public void saveGame(Game aGame) {
File aSaveFile = new File("C:\\prog24178\\dcgames.dat");
FileOutputStream fos = null;
if (!aSaveFile.getParentFile().exists()) {
aSaveFile.getParentFile().mkdir();
}
try {
if (!aSaveFile.exists()) {
aSaveFile.createNewFile();
}
if (aSaveFile.length() > 0) {
fos = new FileOutputStream(aSaveFile, true);
} else {
fos = new FileOutputStream(aSaveFile, false);
}
if (oos == null) {
oos = new ObjectOutputStream(fos);
}
oos.writeObject(aGame);
} catch (FileNotFoundException ex) {
} catch (Exception x) {
System.out.println("Something bad happened" + x);
}
}
感谢您帮助我解决问题。我认为您应该检查两个问题,
1.
fos=新文件输出流(aSaveFile,true)代码>
如果aSaveFile已经有一些数据,而您将另一个对象数据附加到aSaveFile,则其数据将被混淆,您将无法将该对象恢复。
2.oos.writeObject(aGame)代码>
当您完成writeObject()时,应该使用oos.flush()刷新流缓冲区 我知道。我就是这么做的。异常发生在哪里?当我加载时。我明白了:模特。Game@1f0e5b38那就这些了,你在说什么NullPointerException
?这是模型。Game@1f0e5b38
是所有类继承的对象#toString()
的结果。如果需要自定义toString
表示,则需要重写Game
类中的toString()
方法。它修复了错误,但我的文件中还有更多。它只给我模型。Game@77011e14