Search code examples
javaioobjectinputstreameofexception

java - IO on internal class


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.


Solution

  • 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;
        }
    }