我有一个带有姓名和年龄的类(class)
class Person implements serializable {
int age;
String name;
}
我有一个此类的 ArrayList
ArrayList<Person> persons = new ArrayList<Person>
当tomcat关闭时,我将上面的内容保存到本地文件:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(persons);
out.flush();
byte[] objBytes = bos.toByteArray();
File file = new File("./persons.bin");
Files.write(objBytes, file);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
bos.close();
} catch (IOException ex) {
}
}
当 tomcat 启动时,我加载文件:
File file = new File("./persons.bin");
if (!file.exists()) return;
byte[] objBytes = Files.toByteArray(file);
ByteArrayInputStream bis = new ByteArrayInputStream(objBytes);
ObjectInput in = null;
try {
in = new ObjectInputStream(bis);
ArrayList<Person> persons = (ArrayList<Person>) in.readObject();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
以上内容按预期工作。我的问题是,如果稍后向 Person 类添加新属性会发生什么,例如:
class Person implements serializable {
int age;
String name;
String address;
}
我没有使用 Gson,因为它会产生开销,而且我更喜欢将数据保存为二进制。上面的会失败吗?成功但地址为空?会发生奇怪的事情吗?在这种情况下我可以控制做什么吗?
谢谢
编辑:对于我的类(class)
private static final long serialVersionUID = 1L;
最佳答案
它会坏掉的!您必须定义一个serialVersionUID,否则将根据该类的属性创建一个serialVersionUID。因此,如果更改类,serialVersionUID 也会更改。如果 UID 不匹配,则会抛出 InvalidClassException。
保存对象而不是对象的状态会带来很多问题,我建议以更合适的格式保存它们。 JSON、XML 甚至 CSV...说真的,这一点开销将为您避免以后的很多麻烦。
关于Java:本地缓存和更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60554366/