2015-02-17 44 views
-1

我試圖創建一個存儲我正在製作的遊戲的高分的文件。我正在使用序列化程序將我的數組寫入文件。該文件在運行我的代碼時創建,但文件爲空(0字節)。我沒有收到任何錯誤。誰能告訴我爲什麼該文件不包含我的數據?序列化對象文件輸出爲空

public class BestTimes implements Serializable 
{ 
    BestTimes[] beginner = new BestTimes[2]; 

    public static void main(String args[]) throws IOException { 
     BestTimes bestTimes = new BestTimes(); 
     bestTimes.outputToFile(); 
    } 

    public BestTimes() { 
     beginner[0] = new BestTimes(1, "John", 10.5); 
     beginner[1] = new BestTimes(2, "James", 20.3); 
    } 

    public int ranking; 
    public String playerName; 
    public double time; 

    public BestTimes(int r, String p, double t) 
    { 
     ranking = r; 
     playerName = p; 
     time = t; 
    } 

    public void outputToFile() throws IOException { 
     try(FileOutputStream f = new FileOutputStream("bestTimes.txt")) { 
      ObjectOutputStream s = new ObjectOutputStream(f); 
      s.writeObject(beginner); 
      s.flush(); 
      s.close(); 
     } finally { 
      FileOutputStream f = new FileOutputStream("bestTimes.txt"); 
      f.close(); 
     } 

    } 
} 
+0

對於任何人可能會低估我的問題,我很抱歉,如果我的問題做錯了。我很感謝反饋,告訴我我的問題有什麼問題,而不是僅僅對其進行評估。這樣我就不會在未來的問題上犯同樣的錯誤。 – kb4000 2015-02-17 23:39:04

+0

'FileOutputStream f = new FileOutputStream(「bestTimes.txt」); f.close(); ' - 這將打開文件並刪除其內容,然後再次關閉它。所以你成功地寫了這個文件,然後你沒有任何東西覆蓋它。 – immibis 2015-02-17 23:44:21

+0

抱歉,由於誤解了上一個問題的答案,所以我放入了這段代碼。 – kb4000 2015-02-17 23:45:46

回答

2

當然是空的。您在finally區塊中創建了一個新區域。

只需刪除該代碼即可。