I am writing in a BufferedOutputStream three times:
b1 = baos1.toByteArray();
b2 = baos2.toByteArray();
bos.write(b1);
bos.write(b2);
bos.write(b1.length);
System.out.println(b1.length);
System.out.println(b2.length);
bos.flush();
bos.close();
The I want to get the value wrote (b1.length) in another class but the value I get is different from the first *.println().
System.out.println(aux.length); // The entire stream (b1+b2+b1.length)
System.out.println(aux[aux.length - 1]);
For example:
Println 1 --> 123744
Println 2 --> 53858
Println 3 --> 177603
Println 4 --> 96
In that case println1 and println4 should return the same size. What I am doing wrong?
I have checked that 1 byte is wrote (177603-123744-53858 = 1) that is the b1.length byte.
Can someone help me to write correctly the size of the first byte array?
A single
byte
in Java is a signed value with range-128..127
. This is not enough for the value you are trying to store.You should write at least a 4 bytes integer to manage lengths up to
Integer.MAX_VALUE
.What happens is that the value gets truncated to 1 byte, this is easy to see as