jdk1.8源码
public ObjectOutputStream(OutputStream out) throws IOException { verifySubclass(); bout = new BlockDataOutputStream(out); handles = new HandleTable(10, (float) 3.00); subs = new ReplaceTable(10, (float) 3.00); enableOverride = false; writeStreamHeader(); //向文件写入header信息 bout.setBlockDataMode(true); if (extendedDebugInfo) { debugInfoStack = new DebugTraceInfoStack(); } else { debugInfoStack = null; } }
ObjectOutputStream构造方法会调用writeStreamHeader()向文件写入header信息 ,多次创建ObjectOutputStream对象向同个文件writeObject时会多次写入header信息,这使得readObject()时不能持续读取到存入的对象,抛出StreamCorruptedException。
直接重写writeStreamHeader()使其不写入任何内容即可
代码如下
class MyObjectOutputStream extends ObjectOutputStream { public MyObjectOutputStream() throws IOException { super(); } public MyObjectOutputStream(OutputStream out) throws IOException { super(out); } @Override protected void writeStreamHeader() throws IOException { //重写该方法 return; } }
记得第一次向文件writeObject()时,要使用ObjectOutputStream对象,因为第一次一定要写入Header信息,代码如下:
if (file.length() < 1) { //若文件不存在或文件为空使用ObjectOutputStream写入对象 oos = new ObjectOutputStream(new FileOutputStream(file, true)); } else { //文件不为空则用MyObjectOutputStream写入对象 oos = new MyObjectOutputStream(new FileOutputStream(file, true)); }
时间: 2024-10-01 05:42:09