tobloef
tobloef

Reputation: 1891

Add item to serialized list in a file

I have an ArrayList of a Serializable, which I can serialize then save and load it from a file. But what if I want to add an object to the arraylist, without loading the whole list, then saving the whole thing again? I don't feel like loading the whole list, then adding an object to it and then save it again, as it would impact my performance.

These are the two method I've made for saving and loading the file. The Deck class of course implements Serializable.

public static List<Deck> loadDeckDatabase() throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream("decks");
        ObjectInputStream ois = new ObjectInputStream(fis);
        List decList = (List) ois.readObject();
        ois.close();
        return decList;
    }

public static void saveDeckDatabase(List<Deck> decks) throws IOException, ClassNotFoundException {
        FileOutputStream fos = new FileOutputStream("decks");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(decks);
        oos.close();
    }

I hope someone can help me. Thanks!

Upvotes: 4

Views: 1146

Answers (2)

m.antkowicz
m.antkowicz

Reputation: 13581

Why don't you just use SQLite database? It is light, local (stored just in file) database supported by Java. The way you are using it is same that using common database.

Look at the tutorial here: http://www.tutorialspoint.com/sqlite/sqlite_java.htm

If you don't want to use the database I see two ways to dealt with you problem:

  • Keep every array object in other file and keep a files counter in some place - which is not very elegant solution and I guess it will increase I/O operations count
  • Serialize your structure to JSON and write your own method to add element. Since JSON's structure is very simple it seems to be quite easy to just add new element with simple file and string operations

Upvotes: 1

Rob Audenaerde
Rob Audenaerde

Reputation: 20069

Either:

  • You have to load and save, as you don't know how the Deck is serialized.
  • You can to write your own serialization so you actually know how to append.

See also here: https://stackoverflow.com/a/7290812/461499

Upvotes: 1

Related Questions