Receive byte[] using ByteArrayInputStream from a socket

人走茶凉 提交于 2019-11-29 18:28:31

问题


Here is the code but got error:

bin = new ByteArrayInputStream(socket.getInputStream());

Is it possible to receive byte[] using ByteArrayInputStream from a socket?


回答1:


No. You use ByteArrayInputStream when you have an array of bytes, and you want to read from the array as if it were a file. If you just want to read arrays of bytes from the socket, do this:

InputStream stream = socket.getInputStream();
byte[] data = new byte[100];
int count = stream.read(data);

The variable count will contain the number of bytes actually read, and the data will of course be in the array data.




回答2:


You can't get an instance of ByteArrayInputStream by reading directly from socket.
You require to read first and find byte content.
Then use it to create an instance of ByteArrayInputStream.

InputStream inputStream = socket.getInputStream();  

// read from the stream  
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
byte[] content = new byte[ 2048 ];  
int bytesRead = -1;  
while( ( bytesRead = inputStream.read( content ) ) != -1 ) {  
    baos.write( content, 0, bytesRead );  
} // while  

Now, as you have baos in hand, I don't think you still need a bais instance.
But, to make it complete,
you can generate byte array input stream as below

ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() );  


来源:https://stackoverflow.com/questions/10475898/receive-byte-using-bytearrayinputstream-from-a-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!