4

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!

Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
tobloef
  • 1,821
  • 3
  • 21
  • 38

2 Answers2

1

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

Community
  • 1
  • 1
Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
  • I had been considering writing my own way of saving and loading the database. Saving and loading isn't an option, since the ArrayList can easily contain 3,000+ objects, which takes a bit too long to save. – tobloef Sep 08 '15 at 09:29
  • A further alternative is to use database like structures. Make you deck to an entity, so you can easily load, change, add etc your decks with a convenient framework like hibenate – Sergej Werfel Sep 08 '15 at 09:39
  • @Typischserg yes, that is also a kind of serialization (although not through `Serializable`). – Rob Audenaerde Sep 08 '15 at 09:43
1

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
Community
  • 1
  • 1
m.antkowicz
  • 13,268
  • 18
  • 37