遇到的各种异常

java.io.StreamCorruptedException: invalid type code:

这个异常时在io输入输出流的练习中遇到的,为了使写进到文件中的内容不会被覆盖,

代码为ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(
     new FileOutputStream(path,true)));在读取文件时就会遇到这个错误,网上的解答是“一个线程里面同时new了多个ObjectOutputStream流。这在ObjectOutputStream是不允许的,其它的流可以。ObjectOutputStream有锁机制”现在还没有弄明白这个问题。。。

 

 老师给出的解答,是因为往文件里写的时候每写一次就会写一个头文件,这样读的时候读到第二个头文件就会报错,正确的做法是重写ObjectOutputStream方法

public class ObjectSave {

 /**
  * @param args
  * @throws IOException
  * @throws IOException
  * @throws FileNotFoundException
  */
 public static void main(String[] args) {
  ObjectOutputStream out = null;
  ObjectInputStream in = null;

  List<User> list = new ArrayList<User>();
  list.add(new User("admin", "admin", "123", 1));
  list.add(new User("zhang", "zhang", "123", 0));
  String path = "d://abc";
  try {
   
   //判断文件大小并调用不同的方法
   File file = new File(path);
   FileOutputStream fos = new FileOutputStream(file, true);
            if(file.length()<1){
             out = new ObjectOutputStream(fos);
            }else{
             out = new MyObjectOutputStream(fos);
            }
   //out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path,true)));

   //out.writeObject(Calendar.getInstance());
   //判断文件大小并调用不同的方法
   for (int i = 0; i < list.size(); i++) {
    out.writeObject(list.get(i));
   }
  } catch (Exception ex) {
   ex.printStackTrace();
  } finally {
   try {
    out.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

  try {
   in = new ObjectInputStream(new BufferedInputStream(
     new FileInputStream(path)));
    //Calendar date = (Calendar) in.readObject();
    //System.out.format("On %tA, %<tB %<te, %<tY:%n", date);
   while (true) {
    User user = (User) in.readObject();
    System.out.println(user.getName());
   }
  } catch (EOFException e) {
  } catch (Exception ex) {
   ex.printStackTrace();
  } finally {
   try {
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}

 

 

import java.io.*;

class MyObjectOutputStream extends ObjectOutputStream {
 public MyObjectOutputStream() throws IOException {
  super();
 }

 public MyObjectOutputStream(OutputStream out) throws IOException {
  super(out);
 }

 @Override
 protected void writeStreamHeader() throws IOException {
  return;
 }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值