Java – reads a byte array from the socket

I have read the sun guide and different similar questions I want to read some unknown number of bytes from the socket into the array

I have two options. I can use read (byte) in the loop and add bytes to the byte array, or I can use datainputstream readfull (byte []) to read all bytes into the byte array Which is better, and how to find the size of the byte array in advance for allocation? In addition, if I use the first method, how to append bytes to the byte array

while(in.read(b) ! = -1)
{
 //Add to byte array,but how to append at the end?
}

I can use StringBuilder to receive data, attach to it, and execute tostring() getBytes()?

Solution

Read in the block and write it to bytearrayoutputstream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
for(int s; (s=in.read(buffer)) != -1; )
{
  baos.write(buffer,s);
}
byte result[] = baos.toByteArray();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>