对象序列化中遇到的StreamCorruptedException异常及其解决方法


异常产生的原因:使用缺省的serializetion的实现时,一个ObjectOutputStream的构造和一个ObjectInputStream的构造必须一一对应.
ObjectOutputStream的构造函数会向输出流中写入一个标识头,而ObjectInputStream会首先读入这个标识头.
因此,多次以追加方式向一个文件中写入object时,该文件将会包含多个标识头.
所以用ObjectInputStream来deserialize这个 ObjectOutputStream时,将产生StreamCorruptedException.
解决方法:构造一个 ObjectOutputStream的子类,并覆盖writeStreamHeader()方法.
被覆盖后的writeStreamHeader()方法应判断是否为首次向文件中写入object,
否则调用super.writeStreamHeader();
若否,即以追加方式写入object时, 则应调用ObjectOutputStream.reset()方法.
下面是一个具体的例子
import java.io.*;
import java.util.*;
public class UserDao {
    /**
     * 文件路径
     */
    private static final String FILE_PATH = "users.dat";
    // public ObjectOutputStream outSteam;
    public UserDao()  {
    }
    public void saveUser1(User user) throws IOException {
        ObjectOutputStream outSteam = null;
        try {
            // 带有true参数的FileOutputStream
            outSteam = new ObjectOutputStream(new FileOutputStream(FILE_PATH,
                    true)) {
                // 如是果要附加对象到文件后
                // 必须重新定义这个方法
                // 如果不是追加方式这样写后果自负啊
                protected void writeStreamHeader() throws IOException {
                }
            };
            outSteam.writeObject(user);
            outSteam.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outSteam.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void saveUser2(Set<User> users) {
        ObjectOutputStream outSteam = null;
        try {
          
            outSteam = new ObjectOutputStream(new FileOutputStream(FILE_PATH,
                    true)) {
                // 如是果要附加对象到文件后
                // 必须重新定义这个方法
                // 如果不是追加方式这样写后果自负啊
                protected void writeStreamHeader() throws IOException {
                }
            };
            for (User user : users) {
                outSteam.writeObject(user);
            }
            outSteam.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
         try {
             outSteam.close();
         } catch (IOException e) {
         e.printStackTrace();
         }
         }
    }
    // 查询出所有用户
    public void findAllUser() {
        ObjectInputStream ois = null;
        try {
            FileInputStream tempSteam = new FileInputStream(FILE_PATH);
            ois = new ObjectInputStream(tempSteam);
            Object obj;
            while (tempSteam.available() > 0) {// 你原来的这里可是死循环啊
                obj = ois.readObject();
                if (obj instanceof User) {// 建议加上这句
                    User user = (User) obj;
                    System.out.println(user);
                }
            }
        } catch (EOFException e) {
            //
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws Exception {
        UserDao dao = new UserDao();
        User u1 = new User("LILI", 19);
        User u2 = new User("LUCY", 15);
        User u3 = new User("HEHE", 17);
       
        Set<User> users = new HashSet<User>();
        ObjectOutputStream outStream= new ObjectOutputStream(new FileOutputStream(FILE_PATH ));
        users.add(u1);
        users.add(u2);
        users.add(u3);
        System.out.println("方法1:----------------------------------");
        dao.saveUser1(u1);
        dao.saveUser1(u2);
        dao.saveUser1(u3);
        dao.findAllUser();
        System.out.println("方法2:----------------------------------");
        dao.saveUser2(users);
        dao.findAllUser();
    }
}
class User implements Serializable
{
 public User(){}
 public User(String name,int age)
 {
  this.name=name;
  this.age=age;
 }
 public String getName()
 {
  return name;
 }
 public void setName(String name)
 {
  this.name=name;
 }
 public int getAge()
 {
  return age;
 }
 public void setAge(int age)
 {
  this.age=age;
 }
 public String toString()
 {
  return getClass().getName()+"name="+name+",age="+age;
 }
 private String name;
 private int age;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值