I have already read the sun guide and different similar questions. I want to read some unknown number of bytes into an array from Socket.
I have two options either I can use the read(byte) in a loop and add the bytes to byte array or I can use DataInputStream readFully(byte[]) to read all the bytes into byte array. Which one is better and how do I find the size of byte array beforehand for allocation? Also, If I use the first approach how to append the bytes in the byte array.
while(in.read(b) ! = -1)
{
//Add to byte array, but how to append at the end?
}
Can I use StringBuilder to receive the data, append to it and then do toString().getBytes()?
Read in small chunks and write it into ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
for(int s; (s=in.read(buffer)) != -1; )
{
baos.write(buffer, 0, s);
}
byte result[] = baos.toByteArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With