Leo
Leo

Reputation: 3143

int byte to string in java

Problem

I read first byte in my socket client to check connection:

ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteOrder.BIG_ENDIAN);
...
int dataInt = clientSocket.getInputStream().read();

Documentation:

Reads a single byte from this stream and returns it as an integer in the range from 0 to 255. Returns -1 if the end of the stream has been reached.

after that I want to splice this byte with next input string. I convert this integer byte to characters

b.putInt(dataInt);
byte[] dataByte = b.array();
final String data;

and check it. If dataInt != -1, I have to return this croped byte into new string:

if(dataInt != -1)
{
    String c = new String(dataByte);
    Log.v("MSG", c);
    data = c + inToServer.readLine();
}
else
{
    data = inToServer.readLine();
}

Why I see in log "MSG, ������MY MESSAGE"? How to get a string correctly?


Upd, how I send my messages:

byte[] buf = str.getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);
outToServer.writeBytes("\n");
outToServer.flush();

Upvotes: 2

Views: 6390

Answers (4)

Leo
Leo

Reputation: 3143

Omg, I did it. Solution:

byte[] b1 = new byte[1];
int dataInt = clientSocket.getInputStream().read();
b1[0] = (byte)dataInt;

Upvotes: 0

renam.antunes
renam.antunes

Reputation: 770

I would recommend you to use IOUtils.toString for this. It facilitates a lot of the boring and error prone input/output stream manipulation.

Here is an answer explaining how to setup your project to use apache IO commons.

Upvotes: 0

IAmGroot
IAmGroot

Reputation: 13865

Okay, so on your server side just do this with your recieved byte[] There is no need for byte buffers, or to manipulate it in any way.

String str = new String(recievedBytes); 

Upvotes: 1

gordy
gordy

Reputation: 9806

if(dataInt != -1)
{
    String c = new String(dataByte, "UTF-8");
    Log.v("MSG", c);
    data = c + inToServer.readLine();
}
else
{
    data = inToServer.readLine();
}

Upvotes: 2

Related Questions