I'm currently writing a Java game and need to save some data to a file. I'm using DataInputStream
and DataOutputStream
to do the reading and writing for the file. However, while most of the data needing to be written are primitive types, I also have some enums that need to be saved in the file. Is there a way to read and write enums to a file using DataStreams?
Simply use its writeUTF(String str) method. And then don't write the enum itself, but its string representation; for example by calling the name()
method of your enum object.
Of course, that requires a bit of coding on the "reading" part to translate those strings into Enum constants again; but that is exactly where you want to spend your energy.
The ugly truth is: Java enums and serialization that is really nasty topic; as it introduces very hard versioning conflicts if you don't pay attention.
Meaning: the "normal" way that most people would use: do "ordinary" object serialization; create a byte stream; and write those bytes into your DataOutputStream. But in order to make that work, the enum class file needs to match up on both ends. If not, you end up with exceptions deep down in the Java serialization framework; which can be hard to deal with.
So long story short: don't serialize enums directly, instead, send strings around.