Search code examples
javaobjectstoreflat-file

Java: Save objects in a textfile? Are there readymade solutions?


I want to save the objects I generated in a program. After restart the App should load automaticly all Objects in an Array. I want to write them in a file and parse them after restart. Are the other smarter possibilities than do it by hand? Thank you


Solution

  • You can use the Berkeley DB PersistentMap class to save your (Serializable) objects in a Map implementation (a cache) which persists them to a file. It's pretty simple to use and means you don't have to worry about what to save where.

    Three things to note about serialization:

    1. How are you going to cope with schema changes (i.e. changing what data your classes consist of - adding a new field for example)
    2. What happens if your file(s) become corrupted? Depending on how reliable your program's storage needs to be will affect your decision of how you save the data which your objects implicitly contain. Remember, you can always use a relational database such as MySQL and then convert this data into your objects
    3. Do you need to be able to view or query the data outside of your program? What if you want to answer some simple question like "How many object's have property X?" Easy to do if you've used a (relational) database; not so easy if you've serialized stuff to files!