簡體   English   中英

從文件中讀取對象 - 消失的引用

[英]Read Objects from file - vanishing References

我正在嘗試做這樣的事情:

人; PersonList(ArrayList) 包含人;

摘要包含 PersonList;

SummaryList (ArrayList) 包含摘要。

接下來我想修改我的 Person 並將其保存到文件中,如下面的代碼:

//first run
    personList.addPerson(); // PersonArrayList: [Person: Anonymous Person]

    summaryList.addSummary(personList); // SummaryArrayList: [Summary: Test,  PersonArrayList: [Person: Anonymous Person]]

    modifyPerson(personList); // set lastName to ModifiedPerson
    // PersonArrayList: [Person: Anonymous ModifiedPerson]
    // SummaryArrayList: [Summary: Test,  PersonArrayList: [Person: Anonymous ModifiedPerson]]

    save.savePersonListToDatabase(personList);
    save.saveSummaryToDatabase(summaryList);
/*
here is OK. Is one instance of PersonList and one instance of Person. Change in Person affect to both Lists.
end of first run
*/

接下來我想從文件中讀取它。 我使用此代碼從文件中讀取(類似於保存):

public Object readObjectFromFile(String filePath) throws IOException, ClassNotFoundException {
    fileInputStream = new FileInputStream(filePath);
    objectInputStream = new ObjectInputStream(fileInputStream);
    Object object = objectInputStream.readObject();
    System.out.println("Read " + filePath + " is OK");
    objectInputStream.close();
    return object;
}

public PersonList readPersonListFromDatabase() {
    try{
        String personFilePath = "PersonList.obj";
        personList = (PersonList) readObjectFromFile(personFilePath);
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
     return personList;
}

第二次運行:

//second run
    personList = read.readPersonListFromDatabase();
    summaryList = read.readSummaryListFromDatabase();
/*
here is NOT ok. There are two instances of PersonList and two instances of Person. Change in Person does
not affect on SummaryList (because there are different instances of it)
*/

我使用SerializableFileOutputStream / ObjectOutputStream來保存它。

我想運行程序,做我的事情,保存並關閉。 在下一次運行中,我想從文件中讀取所有內容。

如果我想在從文件讀取后保留所有引用,我該怎么辦?

最后,我找到了解決方案。

關注這篇文章https://stackoverflow.com/a/10374665/14558334

我創建了一個“容器”class,它看起來像這樣:

public class ClassContainer implements Serializable {
    private SummaryList summaryList;
    private PersonList personList;

    public ClassContainer(SummaryList summaryList, PersonList personList) {
        this.summaryList = summaryList;
        this.personList = personList;
    }
}

多虧了這一點,我只保存/讀取了一個 object 並保存了所有參考。

也許這不是最好的解決方案,但它工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM