問題描述:在使用java.io.ObjectInputStream類的readObject()方法去讀取包含有序列化了多個(兩個及兩個以上)類的文件時,當讀取到第二個類時,會拋出題目中提到的異常.
原因:任何一個文件都有文件頭(header)和文件體(body),java在以追加的方式寫一個文件時,他每次都會向文件追加一個header,該header是無法識別的,所以回拋出該異常
解決方法:
java提供的對象輸出流無法解決該問題,我們可以自己寫一個java.io.ObjectOutputStream類的子類,該子類如下:
1 public class MyObjectOutputStream extends ObjectOutputStream { 2 3 protected MyObjectOutputStream() throws IOException, SecurityException { 4 super(); 5 } 6 7 @Override 8 protected void writeStreamHeader() throws IOException { 9 10 } 11 12 public MyObjectOutputStream(OutputStream o) throws IOException{ 13 super(o); 14 } 15 }
該類重寫了父類中的writeStreamHeader()方法,該方法用於寫入header信息,這里讓他不進行任何操作,其他的全部使用父類的方法
在邏輯代碼中,判斷要寫入的文件是否是第一次輸入即可,代碼如下:
1 Student s = new Student("godbless", "男"); 2 File file = new File(filePath); 3 ObjectOutputStream oos = null; 4 if (!file.exists()) { 5 file.createNewFile(); 6 } 7 if(file.length()==0){ 8 new ObjectOutputStream(new FileOutputStream(file, true)).writeObject(s); 9 }else{ 10 new MyObjectOutputStream(new FileOutputStream(file, true)).writeObject(s); 11 } 12 System.out.println("序列化完成");