执行如下代码是正常的
static String filePath = "E:\\object.txt";
public static void main(String[] args) {
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
) {
oos.writeInt(20);
oos.writeObject("def");
int o2 = ois.readInt();
System.out.println(o2);
Object o1 = ois.readObject();
System.out.println(o1);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
但是如果执行如下代码,先写对象,再写出int信息,报 EOFException异常
oos.writeObject("def");
oos.writeInt(20);
Object o1 = ois.readObject();
System.out.println(o1);
int o2 = ois.readInt();
System.out.println(o2);
尝试ObjectOutputStream最后执行 writeInt、writeLong等基本数据类型,都会有这种情况
解决方法:
oos.writeObject("def");
oos.writeInt(20);
oos.flush();
Object o1 = ois.readObject();
System.out.println(o1);
int o2 = ois.readInt();
System.out.println(o2);
写完成后,离开执行flush()方法,刷新数据流,更新缓存数据到基本数据流中。