在以下代碼中,我嘗試將序列化對象寫入順序訪問文件。此代碼使用包含在實現「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 !!!");
}
}
}