在Java中,从InputStream获取不具有已知大小的字节数组



我通过套接字发送一个字节数组,并通过DataInputStream接收它。我不知道字节数组的大小,也没有办法检查。我试过这样做:

byte[] content = new byte[ARRAY_SIZE]; 
int something; 
while((something = inFromStream.read()) > 0)  
    output.write(something); 

然而,这仍然意味着我需要知道字节数组的大小。我不想只填写一个巨大的数字(因为从流中接收到的字节数组可能是100,甚至可能是5000000000)。我如何处理这个问题(最好使用标准的Java API/库)?

您可以将byte[]分段发送到OutputStream

byte[] buffer = new byte[1024 /* or some other number */];
int numRead;
while((numRead = inputStream.read(buffer)) > 0) {
    outputStream.write(buffer, 0, numRead);
}

绕过方法-只有逻辑而没有代码示例

getSizeOfInput int countTokens(){

readInput令牌输入计数令牌

return countTokens}

创建一个countTokens 大小的数组

但总而言之——看看链接创建字节数组列表

最新更新