简体   繁体   中英

How to Serialise objects from multiple classes

I am writing a program that uses Serialization to store the program's objects (users, admins, books, etc). I have multiple controllers that control the adding of different objects to different array lists. Example: Login controller controls the adding and removing of users to the system Example: Book controller which controls adding and removing of books to the system

I would like to know the best way of saving all these different objects from different controllers into my serialized file.

Currently, I have been reading the serialized file in each controller to populate the array lists. this is my reading method in the "Book" controller. And I have a save to file method as well however I'm not sure how to implement the ArrayList from different controllers.

private void populateArrayLists() {
    System.out.print("Im here in ArrayList");
    ArrayList<Object> deserialised = new ArrayList<Object>();

    try {
        FileInputStream file = new FileInputStream("info.ser");
        ObjectInputStream inputFile = new ObjectInputStream(file);
        deserialised = (ArrayList<Object>) inputFile.readObject();

        inputFile.close();
        file.close();
    } catch (IOException | ClassNotFoundException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
    books = (ArrayList<Book>) deserialised.get(2);
}
private void saveData() {
    ArrayList<Object> allData = new ArrayList<Object>();

    books.add(book1);
    admins.add(admin1);
    users.add(user1);

    allData.add(users);
    allData.add(admins);
    allData.add(books);

    try {
        FileOutputStream file;
        file = new FileOutputStream("info.ser");
        ObjectOutputStream outputFile = new ObjectOutputStream(file);
        outputFile.writeObject(allData);
        outputFile.close();
        file.close();
        JOptionPane.showMessageDialog(null, "Saved");
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
}

I would like a method of saving all the different objects in different controllers in one place.

Given your question description, I suggest you implement one solution where you make use of the Repository concept in the way described by Domain Driven Design. It allows you to centralize the logic for handling the collection of objects you have so far. Since you decide to use files, I recommend you to have one file per class of objects instead of one file for all your objects collections. Here you can find a basic approach, it can be improved further with generics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM