ObjectOutputStream/ObjectInputStream多个类输入输出总结

介绍:

ObjectOutputStream流是一个字节流,所以它是基于字节的。构造方法里面需要传入一个OutputStream对象。

ObjectOutputStream流和DataOutputStream流一样,写入文件的数据会出现乱码的情况。

需要实例化的类一定要实现Serializable接口。
 

代码样例:

ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("filename"));
o.writeObject(list);
o.close();
ObjectInputStream oi=new ObjectInputStream(new FileInputStream("filename"));
ArrayList<Account>list=new ArrayList<>();
list=(ArrayList<Account>)oi.readObject();
list.add(account);
oi.close();
一般的,通过ObjectOutputStream只在文件中输出一个对象类,
如果要多次输出多个类则会在文件中则每个类之间会自动通过StreamHeader输出4个字节,导致在进行类的读取是出现报错
注 StreamHeader:
protected void writeStreamHeader() throws IOException {
        bout.writeShort(STREAM_MAGIC);
        bout.writeShort(STREAM_VERSION);
    }//一个short 2个字节,两个都是short类型,占4个字节。
改进办法:
方法一:
我们只要不写入StreamHeader不就可以了,这样分别继承ObjectOutputStream和ObjectInputStream,
分别重写writeStreamHeader和readStreamHeader方法,让他们doNothing就Okay了。

public class MyObjectOutputStream extends ObjectOutputStream {

 public MyObjectOutputStream(OutputStream os) throws IOException, SecurityException {
  super(os);
 }

 @Override
 protected void writeStreamHeader() throws IOException {
  super.reset();
 }
}
public class MyObjectInputStream extends ObjectInputStream{

 public MyObjectInputStream(InputStream in) throws IOException {
  super(in);
 }

 @Override
 protected void readStreamHeader() throws IOException, StreamCorruptedException {
 }
}
方法二:
或者 我们在每次从文件中读取类时
通过 byte[4] 每次将这四个字节读出后 再读入到类中

方法三(最为实用):
我们直接将要输入到文件中的所有类储存到List集合中,只在文件中输入一个List类,
而在我每从文件中读类时,也只从文件中读出一个类赋值给List集合,接下来的具体操作只对List集合进行。
代码样例:
ObjectInputStream oi=new ObjectInputStream(new FileInputStream("filename"));
ArrayList<Account>list=new ArrayList<>();
list=(ArrayList<Account>)oi.readObject();
list.add(account);
ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("filename"));
o.writeObject(list);
o.flush();
oi.close();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值