我想重置ObjectOutPutStream以更新新的对象状态。但为什么它不起作用。以下代码输出“BEFORE”而不是“AFTER”?我的代码出了什么问题?
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Serialization {
public static void main(String[] strs) {
String filename = "E:\\myObject.data";
FileOutputStream fos = null;
ObjectOutputStream out = null;
MyObject myObject = new MyObject();
try {
myObject.setValue("BEFORE");
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(myObject);
out.reset();
myObject.setValue("AFTER");
out.writeObject(myObject);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
try {
FileInputStream fis = null;
ObjectInputStream in = null;
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
myObject = (MyObject) in.readObject();
System.out.println(myObject.getValue());
in.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
public static class MyObject implements Serializable {
private static final long serialVersionUID = 5222199410120362372L;
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
答案 0 :(得分:2)
您正在写一个对象的两个副本,但只读一个。如果您阅读了两个对象,您将在之前和之后看到。