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)); }