Java provides methods for saving data permanently. An object that has to be saved has to implement the interface Serializable. But there is one problem with Java's object serialization: The objects can not be changed. If I open such a file, i see some cryptic symbols. But sometimes I also want to change the data outside of a program. What is a good way to store objects if I also want to change it's values outside of the program?
-
2Why do you insist on doing it "outside" your program? The proper way to manipulate serialized files is to deserialize them via the JVM, manipulate, and re-serialize. You don't have to put that functionality into your main program, just into a bit of code that uses the same object class type as your main program. Whether that constitutes "outside" of the program is down to definitions.– Kilian FothFeb 23, 2018 at 13:36
-
This is a very interesting aspect! Do you have literature to study this on detail?– Henry WeinertFeb 23, 2018 at 17:49
-
1I merely meant that using the JDK's code to perform serialization and deserialization is the officially supported way, and therefore guaranteed to work by the language standard. Any other solution could be guesswork, which handles common cases but not rare ones, which may break with every Java update, etc.– Kilian FothFeb 24, 2018 at 6:31
-
@KilianFoth Going out on a limb here, but I'd wager that you haven't read Effective Java yet. Serialisation has a lot of pitfalls and drawbacks.– PeteFeb 27, 2018 at 9:44
1 Answer
Java serialisation is best avoided. It's full of possible security exploits, it doesn't cope well when your class structure is changed and it creates a "hidden" constructor in your class.
It sounds like you want to be able to use some sort of text file format for storing your objects. I would suggest using JSON or XML. But be very careful when reading these files back in - since they can be edited, they should be viewed as untrusted, and you should be very very strict about checking the contents.