我的部分代码:
byte[] bytes = new byte[8000];
final DataInputStream in = new DataInputStream(s.getInputStream());
final int input = in.read(bytes);
我不知道我会收到多少字节。我可以做无限阵列吗?在这种情况下哪种方式最好?
最佳答案
当你阅读时,你不知道有多少数据可用。例如。例如,如果上次写入套接字的大小为 16KB,则您读取的数据可能会小于此值或大于此值。
您必须编写假设您不需要知道的代码。这允许您在数据到达时对其进行处理,而不管数据的长度。
<小时/>如果您希望发送固定长度的数据 block ,请先发送大小。
byte[] bytes = new byte[1024];
final DataInputStream in = new DataInputStream(s.getInputStream());
int length = in.readInt();
if (length > bytes.length) bytes = new byte[length];
in.readFully(bytes, 0, length); // read length bytes or throw an exception.
关于Java无限数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9945196/