从Socket读取一个字节数组 [英] Reading a byte array from Socket
问题描述
我已经阅读了太阳指南和不同的类似问题。我想从Socket中读取一些未知数量的字节到数组中。
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.
我有两个选项,我可以在循环中使用 read(byte)
并将字节添加到字节数组或我可以使用DataInputStream readFully(byte [])
将所有字节读入字节数组。哪一个更好,如何预先找到字节数组的大小进行分配?另外,如果我使用第一种方法如何在字节数组中追加字节。
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?
}
我可以使用StringBuilder接收数据,附加到它然后执行 toString()。getBytes()
?
Can I use StringBuilder to receive the data, append to it and then do toString().getBytes()
?
推荐答案
读入小块和写入 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();
这篇关于从Socket读取一个字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!