Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from InputStream using read vs. IOUtils.copy

I'm trying to use 2 approaches in order to read from InputStream via Bluetooth socket.

The first one is:

InputStream inputStream = bluetoothSocket.getInputStream();
byte[] buffer = new byte[1024];
inputStream.read(buffer);
String clientString = new String(buffer, "UTF-8");

The problem with this one is that now in clientString there's the original message plus "0" until the buffer is full (I can know the length of the message if I'll use the first bytes as indicators but I try not to).

The second one is (Using IOUtils class from Apache Commons IO):

InputStream inputStream = bluetoothSocket.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
String clientString = writer.toString();

The problem with this one is that it stays on the copy line and never continue beyond this point.

So, my question is, what is the different between those approaches and why do I get different results?

The code on the client side is (C# Using 32feet):

client.Connect(BluetoothEndPoint(device.DeviceAddress, mUUID));
bluetoothStream = client.GetStream();                            
if (client.Connected == true && bluetoothStream != null)
{
    byte[] msg = System.Text.Encoding.UTF8.GetBytes(buffer + "\n");
    bluetoothStream.Write(msg, 0, msg.Length);
    bluetoothStream.Flush();
}
like image 965
SharonKo Avatar asked Oct 19 '22 22:10

SharonKo


1 Answers

I'm guessing that IOUtils class is from Apache Commons IO. It copies from inputStream to writer until it reaches the end of the stream (-1 is returned from read method on stream). Your first method just tries to read the maximum of 1024 bytes and then proceeds.

Also the inputStream.read(buffer) will return the number of bytes read. So when you create your String you can use that:

int read = inputStream.read(buffer);    
String clientString = new String(buffer, 0, read, "UTF-8")

You also need to check if the read method returns -1 indicating that the end of the stream is reached.

like image 109
Zoran Regvart Avatar answered Oct 26 '22 23:10

Zoran Regvart