2014-12-26 27 views
0

在以下代碼中,我嘗試將序列化對象寫入順序訪問文件。此代碼使用包含在實現「Serializable」接口的包中的另一個類「Account」,幷包含4個實例變量,即, acc_no,第一個,最後一個和餘額,用於保存個人的姓名,姓名,帳號和餘額。現在我面臨的問題是,當我添加2條或更多條記錄時,我能夠只寫第一條記錄兩次或更多次,並且第二條記錄和後續條目不會保存,即對於執行代碼時的以下條目:在Java中使用序列化(使用writeObject方法)寫入文件

Enter in the following order : 
Account number, first name, last name, balance : 100 russel crowe 1000000 
200 tom hanks 3000000 
300 will smith 4000000 

當我通過反序列化從文件中讀取上述數據它下面的輸出觀察(此處未提及代碼):

100 russel crowe 1000000.0 
100 russel crowe 1000000.0 
100 russel crowe 1000000.0 

然而,當我爲每一個記錄條目我得到創建一個新帳戶對象預期的產出。

所以,我的問題是爲什麼用「writeObject(record)」方法的「記錄」對象只保留第一個條目?爲什麼總是需要創建一個新的Account對象來獲得預期的輸出?對不起,我的懷疑已經過去了很久。希望我已經成功傳達了我想問的問題。

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectOutputStream; 
import java.util.NoSuchElementException; 
import java.util.Scanner; 

import packtest.account.Account; 
public class SerizbleTest { 

    private static ObjectOutputStream obj; 
    public static void main(String[] args) throws IOException { 
     // TODO Auto-generated method stub 
     Scanner in = new Scanner(System.in); 
     Account record = new Account(); 
     System.out.printf("Enter in the following order :%nAccount number, first name, last name, balance : "); 
     try { 
      obj = new ObjectOutputStream(new FileOutputStream("sertest1.ser")); 
      while (in.hasNext()) { 
       //record = new Account(); 
       record.setAccount(in.nextInt()); 
       record.setFirst(in.next()); 
       record.setLast(in.next()); 
       record.setBalance(in.nextDouble()); 
       //System.out.println(record.getAccount()); 
       obj.writeObject(record); 
      } 
     } 
     catch (NoSuchElementException e) { 
      System.out.println("Invalid input entered !!!"); 
      in.nextLine(); //discarding the input 
     } 
     catch (FileNotFoundException e) { 
      System.out.println("File Does not Exist"); 
      in.close(); 
      //obj.close(); 
      System.exit(1); 
     } 
     catch (IOException e) { 
      System.out.println("IOException occurred !!!"); 
     } 
    } 

} 

回答

1

Java序列化設計用於序列化對象圖。每個對象都記錄一個id,如果你寫了兩次相同的對象,它只是記錄你再次寫了那個對象。這就是爲什麼它們與第一個對象完全相同,因爲給定的對象只寫入一次。

兩種解決方案;

  • 每次寫一個新的對象。
  • 呼叫obj.reset();寫入或使用obj.writeUnshared(record);其寫入「非共享」對象到的ObjectOutputStream之間。此方法是相同的的writeObject,不同之處在於它總是給定的對象寫入作爲流中的一個新的,獨特的對象(而不是一個向後引用指向先前串行化實例)。
相關問題