2014-03-01 92 views
2

我正在嘗試使用用戶界面創建一個簡單的程序。來自gui的用戶插入Person實現Serializable類的名字,姓氏和年齡。在文件中寫入多個對象並閱讀它們

一切正常,但只適用於一人,第一人!似乎每次我發送一個新的對象到我的文件,它確實寫入文件,因爲文件的大小越來越大。

的問題是,當我與對象讀取文件返回只有一個,我想返回存儲在MYFILE類人的所有對象。

這裏是我的代碼先睹爲快:

寫對象按鈕:

try { 
    per = new Person(name, sur, age); 
    FileOutputStream fos = new FileOutputStream("myFile", true); 
    ObjectOutputStream oos; 
    oos = new ObjectOutputStream(fos); 
    oos.writeObject(per); 
    oos.flush(); 
    oos.close(); 
    //some other code here 
} catch (IOException e) { 
    //some code here 
} 

閱讀對象按鈕:

try { 
    FileInputStream fis = new FileInputStream("myFile"); 
    ObjectInputStream ois; 
    ois = new ObjectInputStream(fis); 
    try { 
     rper = (Person) ois.readObject(); 
     ois.close(); 
     JOptionPane.showMessageDialog(null, "People:" + rper, "Saved Persons", JOptionPane.INFORMATION_MESSAGE); 
    } catch (ClassNotFoundException e) { 
     //some code here 
    } 
} catch (IOException e) { 
    //some code here 
} 

感謝您的信息!

+0

請學會[格式化你的代碼(http://www.oracle.com/ technetwork/JAVA/JavaSE的/文檔/ codeconvtoc-136057.html)。這個問題將被大多數人忽略,因爲它是不可能讀的。你怎麼知道_your_代碼在做什麼? –

+0

@BoristheSpider我認爲這是超基本的,我甚至需要評論上面的代碼? – Thms

+0

儘管您的問題是關於編寫和閱讀多個人,但我的代碼中完全沒有看到任何循環。 –

回答

3

每次打開文件時,都會寫入一個標題。當輸入流讀取器在首次讀取後看到該頭部時,會引發異常。由於您在異常處理中沒有任何「printStackTrace」調用,因此您沒有看到該錯誤。

解決辦法是,以防止頭部從當您打開流在後續調用獲取寫入。通過在打開文件之前檢查文件的存在來完成此操作,並且如果它已經存在,請使用不寫入標頭的ObjectOuputStream的子類。

 boolean exists = new File("myFile").exists(); 
     FileOutputStream fos = new FileOutputStream("myFile", true); 
     ObjectOutputStream oos = exists ? 
      new ObjectOutputStream(fos) { 
       protected void writeStreamHeader() throws IOException { 
        reset(); 
       } 
      }:new ObjectOutputStream(fos); 

然後你就可以讀取所有的記錄,後面使用一個對象輸入流...

 FileInputStream fis = new FileInputStream("myFile"); 
     ObjectInputStream ois = new ObjectInputStream(fis); 
     while(fis.available() > 0) { 
      try { 
       Object rper = ois.readObject(); 
       JOptionPane.showMessageDialog(null, "People:" + rper, "Saved Persons", JOptionPane.INFORMATION_MESSAGE); 
      } catch (ClassNotFoundException e) { 
       e.printStackTrace(); 
      } 
     } 
     ois.close(); 
+0

非常好,先生,非常感謝。 – Thms

1
FileOutputStream fos = new FileOutputStream("myFile" , true); 

你不能append這樣的文件。在簡短的grammar of the serialization protocol

stream: 
    magic version contents 

contents: 
    content 
    contents content 

你亂拋垃圾多magic number和版本字段,當解串器遇到這些它拋出一個錯誤的文件。您必須讀取所有提交的值並將其複製到新文件中,並在最後寫入新條目。

相關問題