Reputation: 3399
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?
Upvotes: 1
Views: 382
Reputation: 136022
Wrap BufferedOutputStream in DataOutputStream and use its write(byte[])
and writeInt(int)
methods.
Upvotes: 0
Reputation: 3399
I have solved the issue doing this:
bos.write(ByteBuffer.allocate(4).putInt(b2.length).array());
instead of:
bos.write(b1.length);
Now it works and I can retrieve the length.
Upvotes: 0
Reputation: 133587
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
123744 == 0x1E360
0x1E360 & 0xFF == 0x60
0x60 = 96
Upvotes: 3