System.out.println("Hello brave souls!");
I have a few questions about Object Serialization. I am working on a new version of my math game, and forgot to have it save the game mode on the last three sessions. The records are being saved via object serialization, which leads me here. What I want to know is:
1.) Does object serialization somehow keep hold of the time at which the objects were saved to the file? 2.) In changing ANY of the n objects in the file, do you have to load the one you want to change into memory (via cycling through the objects with a loop), change it, and then rewrite EVERY LAST FREAKING OBJECT back to the file? //seems tedious
Serialization serializes an entire object graph. If you are saving a game, you will probably want to call ObjectOutputStream.writeObject(myGame), which will write the entire game object and all non-transient properties it references, recursively.
To change it, load the game into memory using an ObjectInputStream, change a value, and write it back out.
You might also want to chain a GZIPInputStream and GZIPOutputStream if you are dealing with large amounts of data, it can shrink serialized size a good bit.
If you are dealing with really large objects, an embedded database might be a better option, since you can change a single field without loading the whole thing into RAM.
Lastly, if you want to update the timestamp of an object when it's serialized, implement the writeObject method in the Serializable pseudo-interface. Update your timestamp, then call defaultWriteObject on the supplied ObjectOutputStream. This will give you 'last persisted' behavior.
private void writeObject(java.io.ObjectOutputStream out) throws IOException
1.) Does object serialization somehow keep hold of the time at which the objects were saved to the file?
No. It saves the object and only the object, plus whatever it needs to reconstitute it, such as its class name.
2.) In changing ANY of the n objects in the file
You can't change any of the N objects in the file. You have to reconstitute the file as objects, change the object(s), and reserialize.
// seems tedious
It is tedious. Nobody said it wouldn't be tedious. You are using it as a database. It isn't. It is a serialization, which also implies that it is a stream. Exactly the same applies to a text file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With