2014-03-31 71 views
-2

加載此文件時,我總是得到NullPointerException。我嘗試了很多東西,但我找不到解決問題的方法。當我保存時,我使用了Game對象。讀取文件時出現NullPointerException

 @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); 
     } 
    } 

謝謝你幫我解決我的問題。

+0

[什麼是'NullPointerException'?](我知道這是什麼意思?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception) –

+0

我知道。這就是我所做的。 –

+0

異常發生在哪裏? –

回答

0

我覺得有兩個問題ü應該檢查,


如果aSaveFile已經有一些數據和u追加另一個對象的數據aSaveFile,其數據將被迷惑,日子會把不能帶上對象回來了。

2. oos.writeObject(aGame);
當你完成writeObject()時,你應該使用oos.flush()刷新流緩衝區;

+0

它修復了錯誤,但我有更多的文件。它只給我[email protected] –

相關問題