【问题标题】:ObjectInputStream readobject doesnt work OptionalDataExceptionObjectInputStream readobject 不起作用 OptionalDataException
【发布时间】:2016-04-20 13:50:35
【问题描述】:

当我使用 readObject 时,我得到 OptionalDataException(当流中的下一个元素是原始数据时,试图读取一个对象),我该如何解决这个问题?页面是可序列化的。 writeObject 有效。

public Map<Long,Page<byte[]>> readAllPages(){

        ObjectInputStream in = null;
        try
        {
            in= new ObjectInputStream(new FileInputStream(HardDisk.getDefault_File_Name()));
            @SuppressWarnings("unchecked")
            Map<Long, Page<byte[]>> readMap = (Map<Long, Page<byte[]>>)in.readObject(); // exception here
            return readMap;
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            System.exit(0);
            return null;
        }
        finally
        {
            if(in != null)
            {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

public void writeAllPages(Map<Long,Page<byte[]>> hd){
        ObjectOutputStream out = null;
        try
        {
            out = new ObjectOutputStream(new FileOutputStream(HardDisk.getDefault_File_Name()));
            out.writeObject(hd);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
            System.exit(0);
        }
        finally
        {
            if(out != null)
            {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

【问题讨论】:

  • Page 是否有自定义读取和/或写入方法?
  • 什么意思?页面有 getter 和 setter,但没有 write 或 read 方法
  • 您是否尝试反序列化在 Page 类不同时序列化的对象?
  • 不,这些是代码中唯一使用 readObject 和 writeObject 的地方。
  • 我已经删除了文件并使用writeObject再次创建它,没有问题然后使用readAllPages方法,问题仍然存在。我添加了调用方法的代码。

标签: java objectinputstream optionaldataexception


【解决方案1】:

问题是具有read方法的类扩展了ObjectInputStream所以我不应该也创建“in”对象,我删除它并用“this”交换它,问题就解决了!

【讨论】:

    猜你喜欢
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2012-02-27
    相关资源
    最近更新 更多