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?