Is it possible to avoid the "junk" values?
Yes. Write out an int
, not an Object
. By passing an int
to writeObject
, you're promoting it (autoboxing it) to Integer
, which means that the serialized information contains header information saying that it's an Integer
object, not an int
. Your ByteArrayOutputStream
has a write(int)
method that writes a byte (the low-order 8 bits of the int) to the output stream. Whether those are signed or not is purely a matter of interpretation, not the bits in the stream.