i am working with ObjectOutputStream
to save my object to a .dat
file.
My problem is, that if i CHANGE source code of my object (for example i add ONE method(getter)) the
input stream cannot load data and tell me a error about Serializable
:
It is possible to solve this problem? I must generate new .dat
file everytime after if i change my source code.
Using this method: (DONT LOOK AT THE OBJECT TYPE-return value) SAVE
public void saveToFile(HeaderOfMapTeachStructure hm, String nameOfFile) {
try (ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream(nameOfFile + "." + this.TYPE_OF_FILE))) {
os.writeObject(hm);
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
LOAD
public MapStandard loadFromFileMS(String nameOfFile) {
MapStandard hm = null;
InputStream inputStreaminputStream
= getClass().getClassLoader().
getResourceAsStream("data/" + nameOfFile + ".data");
try {
try (ObjectInputStream is = new ObjectInputStream(inputStreaminputStream)) {
hm = (MapStandard) is.readObject();
}
} catch (IOException | ClassNotFoundException e) {
System.out.println("Error: " + e);
}
return hm;
}
ERROR IS:
Error: java.io.InvalidClassException: MapVerb.RealVerb; local class incompatible: stream classdesc serialVersionUID = -887510662644221872, local class serialVersionUID = 7992494764692933500
It is possible to solve this problem?
Yes. The reason the serialization breaks is because the generated version number changes. If you specify this explicitly, it won't be generated, and you'll be in control of versioning. That means you need to be careful though - if you change the fields which are in the object, or the meaning of those fields, you'll need to remember to change the version number yourself.
You specify the serialization version like this:
// It doesn't have to be constant, but that's fairly common.
private static final long serialVersionUID = ...; // Some constant
See the documentation for Serializable
for more information.
You might also want to consider using alternative approaches for storing data - the default binary serialization in Java is fairly brittle. There are lots of alternatives - text-based formats such as XML, JSON or YAML, or binary formats such as Protocol Buffers or Thrift.
See more on this question at Stackoverflow