對象反序列化時,拋出java.io.StreamCorruptedException: invalid type code: AC異常


  問題描述:在使用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("序列化完成");        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM