Search code examples
javaobjectinputstreamoptionaldataexception

ObjectInputStream readobject doesnt work OptionalDataException


when I use readObject I get OptionalDataException (An attempt was made to read an object when the next element in the stream is primitive data), how do I fix this? Page is Serializable. writeObject works.

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();
                }
            }
        }
    }

Solution

  • The problem was that the class that has the read method extends ObjectInputStream so I shouldn't also create the "in" object, I deleted it and exchanged it with "this" and the problem was solved!