Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive byte[] using ByteArrayInputStream from a socket

Here is the code but got error:

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

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

like image 853
hkguile Avatar asked May 07 '12 02:05

hkguile


People also ask

How do you read data from ByteArrayInputStream?

Example: ByteArrayInputStream to read data ByteArrayInputStream input = new ByteArrayInputStream(array); Here, the input stream includes all the data from the specified array. To read data from the input stream, we have used the read() method.

How do I print a byte array?

You can simply iterate the byte array and print the byte using System. out. println() method.

What is a ByteArrayInputStream?

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method. Closing a ByteArrayInputStream has no effect.


1 Answers

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.

like image 59
Ernest Friedman-Hill Avatar answered Oct 22 '22 10:10

Ernest Friedman-Hill