原因:
使用缺省的serializetion的实现时,一个ObjectOutputStream的构造和一个ObjectInputStream的构造必须一一对应,ObjectOutputStream的构造函数会向输出流中写入一个标识头,而ObjectInputStream会首先读入这个标志头,因此,多次以追加方式向一个文件写入Object时,该文件将会包含多个标志头,所以用ObjectInputStream来deserialize这个ObjectOutputStream时,将产生StreamCorruptedException。
解决方案:
写自己的MyObjectOutputStreamMyObjectInputStream实现ObjectOutputStream ObjectInputStream.
如下代码:
class MyObjectOutputStream extends ObjectOutputStream {public MyObjectOutputStream(OutputStream out) throws IOException {super(out);// TODO Auto-generated constructor stub
}@Override
protected void writeStreamHeader() throws IOException {// TODO Auto-generated method stubreturn;
}}class MyObjectInputStream extends ObjectInputStream{public MyObjectInputStream(InputStream in) throws IOException {super(in);// TODO Auto-generated constructor stub
}@Override
protected void readStreamHeader() throws IOException,StreamCorruptedException {// TODO Auto-generated method stubreturn;
}
}
``
然后把使用ObjectOutputStream ObjectInputStream的地方改为MyObjectOutputStreamMyObjectInputStream即可。其余方法正常调用。
本文发布于:2024-01-29 12:11:15,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170650147915190.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |