微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java.io.StreamCorruptedException:无效的类型代码:AC

参见英文答案 > StreamCorruptedException: invalid type code: AC1
我正在尝试从文件中读取一些对象.该代码对于第一次迭代工作正常,在第二次迭代时它会给出一个StreamCorruptedException.这是我的代码,
private ArrayList<Cheque> cheques = null;
ObjectInputStream ois = null;
        try {
            cheques = new ArrayList<Cheque>(4);
            ois = new ObjectInputStream(new FileInputStream("src\\easycheque\\data\\Templates.dat"));
            Object o = null;
            try {
                o = ois.readobject();
                int i=1;
                while (o != null) {
                    cheques.add((Cheque) o);
                    System.out.println(i++); // prints the number of the iteration
                    o = ois.readobject(); // exception occurs here
                }
            } catch (ClassNotFoundException ex) {// for ois readobject()
                Logger.getLogger(TemplateReader.class.getName()).log(Level.SEVERE,null,ex);

            } catch (EOFException ex) {// for ois readobject()
                // end of the file reached stop reading
                System.out.println("ois closed");
                ois.close();

            }
        } catch (IOException ex) {
            Logger.getLogger(TemplateReader.class.getName()).log(Level.SEVERE,ex);
        }

以下是异常的一部分.在打印之前,打印“1”(因为south)

SEVERE: null
java.io.StreamCorruptedException: invalid type code: AC
    at java.io.ObjectInputStream.readobject0(ObjectInputStream.java:1356)
    at java.io.ObjectInputStream.readobject(ObjectInputStream.java:351)

我不知道为什么会发生这种情况.在几个论坛帖子中,我发现在写入文件时,会发生这种情况.这是真的原因吗? (我在写作阶段追加到档案).
是否有正确的方法来读取附加文件

这里是我用来写入文件代码

ObjectOutputStream objectOut = new ObjectOutputStream(new FileOutputStream("src\\easycheque\\data\\templates.dat",true));

 objectOut.writeObject(cheque);
 objectOut.flush();
 objectOut.close();

写作不是一个迭代的过程.

谢谢 :)

解决方法

(I am appending to the file during writing pahse)

这就是问题.您无法追加到ObjectOutputStream.这将会明确地破坏流,并获得StreamCorruptedException.

但是我已经在这个问题上已经解决了这个问题:一个AppendableObjectOutputStream

编辑

从作者我看到你写一个检查对象并冲洗并关闭流.从读者看,我清楚地看到,你正在尝试阅读多个检查对象.你可以阅读第一个但不是其余的.所以对我来说,这是非常清楚的,你重新打开流并附加越来越多的检查对象.哪个是不允许的

您必须在“一个会话”中写入所有检查对象.或者使用AppendableObjectOutputStream代替标准的ObjectOutputStream.

原文地址:https://www.jb51.cc/java/124366.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐