ObjectOutputStream 多次写同一个文件后,读取出错解决办法

来源:互联网 发布:.net和java的区别 编辑:程序博客网 时间:2024/05/15 13:00

流对象ObjectOutputStream每次写入数据时,默认情况都会添加头信息,实际上,头信息只需要写一次,之后不需要。

解决方案有2种:

1,新建一个类,让他继承ObjectOutputStream,重写writeStreamHeader方法

 

<p>public class MyObjectOutputStream extends ObjectOutputStream { //定义成静态的好处 private static File f;</p><p> /**  * 初始化静态文件对象,并返回类对象  * @param file 文件对象,用于初始化静态文件对象  * @param out 输出流  * @return MyObjectOutputStream  * @throws IOException  */ public static  MyObjectOutputStream newInstance(File file, OutputStream out)   throws IOException {  f = file;//本方法最重要的地方:构建文件对象,是两个文件对象属于同一个  return new MyObjectOutputStream(out, f); }</p><p> @Override protected void writeStreamHeader() throws IOException {  if (!f.exists() || (f.exists() && f.length() == 0)) {   super.writeStreamHeader();  } else {   super.reset();  }</p><p> }</p><p> public MyObjectOutputStream(OutputStream out, File f) throws IOException {  super(out); }</p><p>}</p>


 

2, 创建ObjectOutputStream对象时,按具体情况分别处理:

long fileSize = new File("E:/a.dat").length();if (fileSize > 0) {oos = new ObjectOutputStream(new FileOutputStream("E:/a.dat",true)) {// 重写 writeStreamHeader()方法,空实现protected void writeStreamHeader() {};};} else {oos = new ObjectOutputStream(new FileOutputStream("E:/a.dat",true));}for (int i = 0; i < 10; i++) {oos.writeObject(new Abc(i, i));}oos.flush();oos.close();


 

0 0