我正在进行序列化,但我无法理解以下内容:
我不明白为什么这段代码的输出是:
import java.io.*;
public class InnerOuterTest {
public static ObjectOutputStream out;
public static ObjectInputStream in;
static {
try {
out = new ObjectOutputStream(new FileOutputStream("save.ser"));
in = new ObjectInputStream(new FileInputStream("save.ser"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
try {
ShouldForgive f = new ShouldForgive();
f.x = 5;
write(f);
ShouldForgive g = read();
System.out.println(g.x);
f.x = 0;
g.x=8;
write(f);
ShouldForgive v = read();
System.out.println("is "+v.x);
} finally {
out.close();
in.close();
}
}
private static void write(ShouldForgive f) throws IOException {
out.writeObject(f);
}
public static ShouldForgive read() throws ClassNotFoundException, IOException {
return (ShouldForgive) in.readObject();
}
}
class ShouldForgive implements Serializable {
int x = -1;
}
是
5
8
并不是
5
0
我尝试f == g
了返回false,如果我重置输入流。我发现如果我实现readObject
它只会被调用一次......我不明白这种行为。(为什么对象只读取一次?)
我觉得序列化只发生一次......对象是如何跟踪的?即使我实现readObject
并且writeObject
没有从文件中实际读取或写入,我仍然得到8