Inputstream error while trying to read bytes [closed] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Inputstream error while trying to read bytes [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am converting a png image to byte array and sent it using sockets to client on android On android i read the bytes as shown bellow:

ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream();
InputStreamReader in = new InputStreamReader(s.getInputStream());
int readLength;
byte buffer[] = new byte[1024];
while ((readLength = in.read(buffer)) != -1) {
 dataBuffer.write(buffer, 0, readLength);
 }
byte bitmapdata[] = dataBuffer.toByteArray();

But i have a very stupid problem here. Java gives me error that it can not accept a byte array for in.read(buffer) For some reason it seems that it only accepts char[], says “Can not resolve method read(byte[])”.

Anyone know why is that happening or any other way i can do this ?

Answer

Since Java supports Unicode, a single Java char is at least two bytes long, and sometimes longer (gory details here). This means that we can’t treat these data types interchangeably as we can in other languages such as C.

Since you want to deal with raw bytes, stay away from InputStreamReader and work directly with the InputStream provided by your Socket.

Something like this should work:

ByteArrayOutputStream dataBuffer = new ByteArrayOutputStream();
InputStream in = s.getInputStream();
int readLength;
byte buffer[] = new byte[1024];
while ((readLength = in.read(buffer, 0, buffer.length)) != -1) {
  dataBuffer.write(buffer, 0, readLength);
}
byte bitmapdata[] = dataBuffer.toByteArray();

If you were expecting to read text instead of image data from your Socket, InputStreamReader would be the way to go, as it hides away many of the headaches relating to variable-byte character encoding formats (more info here)

We are here to answer your question about Inputstream error while trying to read bytes [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji