Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a byte array from Socket

Tags:

java

sockets

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()?


1 Answers

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();
like image 54
kan Avatar answered Aug 23 '26 04:08

kan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!