2011-06-09 160 views
0

我退出活動時保存了一些內容。 首先在一個對象中,第二個是一個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 
       } 
     } 

    } 

回答

2

我從來沒有在Java中使用這些類,但我會冒險猜測。我懷疑這個問題是Java中的int和Integer之間的區別。

在寫代碼,你有沒有試着用

output.writeInt(ScoringForScoreloop.getScore()); 

這樣,你應該是讀對稱和類型處理方面寫更換

output.write(ScoringForScoreloop.getScore()); 

+0

完美!非常感謝。 – theblitz 2011-06-09 22:58:11