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

 反序列化同理:

 1 public class MyObjectInputStream extends ObjectInputStream {
 2     protected MyObjectInputStream() throws IOException, SecurityException {
 3         super();
 4     }
 5 
 6     @Override
 7     protected void readStreamHeader() throws IOException, StreamCorruptedException {
 8     }
 9 
10     public MyObjectInputStream(InputStream in) throws IOException {
11         super(in);
12     }
13 }

 验证读取效果:

 1 public class IOTest {
 2     public static void main(String[] args) throws Exception{
 3         FileInputStream fis = new FileInputStream("1.txt");
 4         MyObjectInputStream ois = new MyObjectInputStream(fis);
 5         while(fis.available()>0) {
 6             System.out.println(ois.readObject());
 7         }
 8         ois.close();
 9         fis.close();
10     }
11 }

 

转载于:https://www.cnblogs.com/hellsino/p/11551920.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值