加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 16:45:24 所属栏目:Java 来源:网络整理
导读:参见英文答案 StreamCorruptedException: invalid type code: AC1 我正在尝试从文件中读取一些对象.该代码对于第一次迭代工作正常,在第二次迭代时它会给出一个StreamCorruptedException.这是我的代码, private ArrayListCheque cheques = null;ObjectInputSt
参见英文答案 > 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("srceasychequedataTemplates.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("srceasychequedatatemplates.dat",true));

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

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

谢谢 :)

解决方法

(I am appending to the file during writing pahse)

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

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

编辑

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读