zoukankan      html  css  js  c++  java
  • 对象反序列化时,抛出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("序列化完成");        
  • 相关阅读:
    HLS视频直播
    CocoaPods版本升级
    项目管理:CocoaPods建立私有仓库
    cocospod 安装和使用
    sqlite加密
    socket的心跳包机制
    iOS开发必备HUD(透明指示层)
    iOS 第一次安装应用,拒绝相机调用,页面卡死的解决方案
    UINavigationController侧滑滑动返回 卡死问题
    第四周学习进度
  • 原文地址:https://www.cnblogs.com/ouhaitao/p/7683514.html
Copyright © 2011-2022 走看看