views:

81

answers:

2

Is it possible to ObjectOutputStream/ObjectInputStream an internal class? I can write it OK, and examine the created file, but when I try to read it back in using ObjectInputStream, I get an EOFException just trying to read an Object o = oos.readObject();

  1. I use the same File object to open both streams, so that's not the problem.
  2. It seems to be independant of the nature of the internal Class - a class with just a public int fails identically to a more complex class.

I have to move on, and create a regular class, and instantiate in the sender class, but I hate to walk away not knowing if it is possible, and if not why not.

Update: Related issues that were the cause of the problem:

A. You cannot re-open a file written with an ObjectOutputStream and append: a second header is written and corrupts the file.

B. Serializing a HashMap using ByteOutputStream to do a hash digest doesn't work, because when you read the HashMap back in from a ObjectOutputStream file, you may very well get a different byte[] from ByteOutputStream because of variations in pair order: the content is the same, but the byte[] (and so the hash disgest) is not.

Hope this helps someone save some time.

+2  A: 

Can you include a small bit of sample code? The most obvious explanation is that you're not closing / flushing the output stream before you try to read it back in.

Jherico
The output stream is closed. The code is on a closed-network machine, so it could be transcribed, but that code is not straightforward. I am not clear on why not closing the stream would be applicable here - if the stream were not closed, the problem would also show when outer classes were used, wouldn't it?
cvsdave
+1  A: 

This one works for me. Please look for any differences to your solution.

public class Example implements Serializable {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        new Example().run();
    }

    private void run() throws IOException, ClassNotFoundException {
        Inner inner = new Inner();
        inner.x = 5;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream( out );
        outputStream.writeObject( inner );

        ByteArrayInputStream in = new ByteArrayInputStream( out.toByteArray() );
        ObjectInputStream inputStream = new ObjectInputStream( in );
        Inner inner2 = (Inner) inputStream.readObject();

        System.out.println( inner2.x );
    }

    class Inner implements Serializable {
        int x;
    }
}

tangens
Thanks - my question was "is it possible" - the answer is clearly yes. Do you have anything on Tom Hawlin's comment about the spec saying not to serialize Inner classes?
cvsdave