亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

可在 ArrayList 上序列化,丟失一些數據

可在 ArrayList 上序列化,丟失一些數據

慕萊塢森 2022-08-03 10:40:01
我有一個 Employee 對象的 ArrayList,其中 Employee 類實現了 Serializable。我正在使用此代碼將列表寫入文件:ArrayList<Employee> empList = new ArrayList<>();  FileOutputStream fos = new FileOutputStream("EmpObject.ser");  ObjectOutputStream oos = new ObjectOutputStream(fos);  // write object to file  empList .add(emp1);  empList .add(emp2);  oos.writeObject(empList);  empList .add(emp3);  oos.writeObject(empList);}如果我嘗試反序列化它,我只得到前兩個對象,而不是第三個對象。任何人都可以嘗試為什么它?edit1:如果我一次添加所有元素,一切都很好,但不是我第一次做的方式。有什么區別?ArrayList<Employee> empList = new ArrayList<>();  FileOutputStream fos = new FileOutputStream("EmpObject.ser");  ObjectOutputStream oos = new ObjectOutputStream(fos);  // write object to file  empList .add(emp1);  empList .add(emp2);  empList .add(emp3);  oos.writeObject(empList);}在此之后,我有3個元素
查看完整描述

2 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

正如GhostCat和uaraven已經提到的,重置并不是你所期望的,你應該看看關于序列化的教程,也許可以考慮使用sth。否則,如果這不適合您的用例。


如果創建新的 FileOutputStream,您的代碼可能如下所示:


import java.io.*;

import java.util.ArrayList;

import java.util.List;


public class SerializationTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        String path = "EmpObject.ser";


        ArrayList<Employee> empList = new ArrayList<>();

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));


        empList.add(emp1);

        empList.add(emp2);

        oos.writeObject(empList);


        empList.add(emp3);

        // Create a new FileOutputStream to override the files content instead of appending the new employee list

        oos = new ObjectOutputStream( new FileOutputStream(path));

        oos.writeObject(empList);


        ObjectInputStream objectinputstream = new ObjectInputStream(new FileInputStream(path));

        List<Employee> readCase = (List<Employee>) objectinputstream.readObject();


        System.out.println(readCase);

    }

}


查看完整回答
反對 回復 2022-08-03
?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

您的代碼會發生什么情況:

  • 您將列表寫入文件,其中包含個條目

  • 您重置流

  • 你再次寫列表,有個條目

因此,您的文件包含個值,是的。兩個列表,一個包含 2 個,一個包含 3 個條目。

換句話說:不會重置已寫入文件的內容!您編寫了一個包含兩個條目的列表。您只是在重置有關存儲對象的信息,以便再次完全序列化 emp1 和 emp2。如果沒有對重置的調用,JVM 將理解它不需要再次完全序列化 emp1 和 emp2。reset()

含義:默認情況下,JVM 壓縮要傳輸的數據量。它記住哪些對象已經寫入,而不是重復寫入它們,它只將類似“之前序列化的對象X再次出現”之類的東西寫入流中。

所以:我認為你根本不理解方法的意義。解決方案:閱讀一個小教程,就像教程點中的一。reset()

根據OP的最新評論進行編輯:

你所要求的東西以這種方式是不可能的。您正在編寫列表對象。這意味著此時該列表的所有條目都將寫入文件。JVM 記住“該列表已經寫好了”,所以即使其內部狀態在此期間發生了變化,它也不會再寫它。


查看完整回答
反對 回復 2022-08-03
  • 2 回答
  • 0 關注
  • 184 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號