【问题标题】:Exception StreamCorruptedException: invalid type code: AC [duplicate]异常 StreamCorruptedException:无效类型代码:AC [重复]
【发布时间】:2023-04-07 14:06:01
【问题描述】:

我想在每次运行程序时序列化文件中的同一个对象。这是一个简单的算法来解释我的问题。

在开始时,我将String 存储在writer 上。在最后我读了一个文件。 这个程序的目标是,如果我运行我的程序 X 次,我存储并在屏幕上打印 X 次我的对象。

class ReadFile {

    static ObjectOutputStream writer = null;

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        writer = new ObjectOutputStream(new FileOutputStream("trace", true));
        store("String");

        if (writer != null) {
            writer.close();
        }

        open("file.tmp");

    }

    static public void store(String chaine) {
        if (writer == null) {
            return;
        }
        try {
            writer.writeObject(chaine);
        } catch (IOException ex) {
        }
    }

    static public void open(String file) throws FileNotFoundException, IOException, ClassNotFoundException {
        StringBuilder str = new StringBuilder();
        ObjectInputStream objs;
        try {

            objs = new ObjectInputStream(new FileInputStream(file));
            try {
                while (true) {
                    Object obj = objs.readObject();
                    str.append(obj.toString());
                }
            } catch (EOFException ex) {
            }
            objs.close();

        } catch (Exception ex) {
            ex.printStackTrace(System.err);
        }
    }
}

当我运行这个程序时,我遇到了这个错误:

java.io.StreamCorruptedException: invalid type code: AC
        at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1355)
        at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
        at ReadFile.open(ReadFile.java:47)
        at ReadFile.main(ReadFile.java:35)

请问我该怎么办?

【问题讨论】:

  • 您应该检查异常并查看它们是否包含任何可能指向问题的有用信息,而不是捕获异常并丢弃它们。另外,这段代码的第 35 行是哪一行?
  • 第 35 行是:open("file.tmp");
  • 为什么不先将所有对象读入列表,然后添加要附加的对象,然后再写回文件。我知道这很耗时而且做得过多,但它在我的情况下有效。看这里link

标签: java file objectoutputstream objectinputstream


【解决方案1】:

根据this 的帖子,您无法附加到 ObjectOutputStream,您试图通过以附加模式打开底层 FileOutputStream 来执行此操作。该帖子中提到了一个解决方案,您可以创建一个 AppendableObjectOutputStream ,或者您可以直接打开 FileOutputStream 而无需附加。

【讨论】:

    猜你喜欢
    • 2011-01-24
    • 1970-01-01
    相关资源
    最近更新 更多