Receive byte[] using ByteArrayInputStream from a socket
Asked Answered
N

2

10

Here is the code but got error:

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

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

Nydianye answered 7/5, 2012 at 2:9 Comment(2)
"but got error:" Got what error? Always copy/paste exception & error output into the question (using code tags).Tion
Your question doesn't make sense. A ByteArrayInputStream reads bytes from a byte array. If you want to read from a socket you can't read from an array of bytes. What problem are you trying to solve here?Prophylactic
C
26

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.

Codel answered 7/5, 2012 at 2:18 Comment(3)
Whats the significance of the number 100 in "new byte[100]" Will I over allocate or underallocate with the 100Chasseur
It’s the size of the array, hence the maximum number of bytes that’ll be read at once. You can use any size you like, and you can read in a loop until you hit the end of the file (count will become -1 at that point.)Codel
Thanks @Ernest. That Makes senseChasseur
M
11

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() );  
Maimonides answered 7/5, 2012 at 2:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.