1

I'm having hard times understanding the behaviour of Output/Input streams in Java.

ObjectOutputStream implements DataOutput interface so, as DataOutputStream, it has the methods to write primitives.

But reversing the written bytes ObjectInputStream throws EOF.

    byte array[]=new byte[50];
    byte value=2;
    System.out.println(value); //prints 2


    ByteArrayOutputStream os=new ByteArrayOutputStream();
    ObjectOutputStream oss=new ObjectOutputStream(os);
    oss.writeByte(value);

    array = os.toByteArray();

    //get back the original value from the byte array
    ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(array));
    byte result=ois.readByte(); // -> throws EOF Exception (see below)

    System.out.println("Result -> "+result);

Throws this Exception

Exception in thread "main" java.io.EOFException
    at java.io.DataInputStream.readInt(DataInputStream.java:392)
    at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2827)
    at java.io.ObjectInputStream.readInt(ObjectInputStream.java:971)
    at z.reti.TestOOS.main(TestOOS.java:21)

Same Exception is thrown using other primitives. Replacing the primitive byte with the Byte wrapper class (and using Read/WriteObject) the problem is gone...

Is there a way to use ObjectOutputStream and ObjectInputStream with primitives?

1 Answer 1

2

You are not closing your ObjectOutputStream. Just add oss.close() after you do oss.writeByte(value) and your program should work as expected.

Sign up to request clarification or add additional context in comments.

2 Comments

that's correct. Why using writeObject the problem didn't appear?
@Z856 Probably because the stream is flushed in that case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.