对象反序列化时,抛出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("序列化完成");        

 

posted @ 2017-10-17 19:42  随花四散  阅读(11544)  评论(0编辑  收藏  举报