您的位置:首页 > 编程语言 > Java开发

连续向文件中写入java对象后,读取报错

2017-04-18 23:49 645 查看
今天遇到个问题,向dat文件中写入java对象,关闭文件,下次再打开文件,继续写入对象,读取时就会报错。

读取第二个对象时报错:

java.io.StreamCorruptedException: invalid type code: AC

    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1377)

    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)

    at com.chennei.test.ReadObjectTest.read(ReadObjectTest.java:90)

    at com.chennei.test.ReadObjectTest.main(ReadObjectTest.java:20)

这是因为ObjectOutputStream写文件时会追加一个文件头,第二次再追加对象时依然会加入文件头。读取时,读到文件头部分就会报错。

解决办法:可以自己继承一个ObjectOutputStream然后覆写writeStreamHeader()方法,然后什么也不干,该方法就是用来写文件头的。

public class AddObjectOutPutStream extends ObjectOutputStream {

    protected AddObjectOutPutStream() throws IOException, SecurityException {

        super();

    }

    protected AddObjectOutPutStream(OutputStream out) throws IOException, SecurityException {

        super(out);

    }

    @Override

    protected void writeStreamHeader() throws IOException {

      //do nothing

     }

}

写文件时,判断是不是第一次写,如果是,用默认的objectoutputstream写,不然用自己定义的AddObjectOutPutStream写,代码

        FileOutputStream fos = null;

        ObjectOutputStream os = null;

        try {

        

            File file = new File();

            if (!file.exists())

            {

                file.createNewFile();

            }

            

            fos = new FileOutputStream(file, true);

            if (file.length() > 0)

            {

                os = new AddObjectOutPutStream(fos);

            } else

            {

                os = new ObjectOutputStream(fos);

            }

            

            List<Apple> list = createApple();

            os.writeObject(list);

            os.flush();

            } catch (Exception e) {

            e.printStackTrace();

        } finally

        {

            try {

                os.close();

                fos.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dat java写文件 java