0

I have a byte array of size 200 that has data received with socket.receive(). Let's say the packet data is "hello".

int size = 200;
DatagramPacket packet = new DatagramPacket(new byte[size], size);
socket.receive(packet);
byte[] byte1 = packet.getData();

I tried to convert the byte array into string, and the string length is 200 even though it prints out only 'hello' string.

String result = new String(byte1); // .toString();
System.out.println(result.length()); --> 200
System.out.println(result); ---> hello

How can I truncate the String to contain only "hello" when converting it from byte[]?

ADDED

Based on malchow's answer, this solved my issue:

int packetLength = packet.getLength();
byte[] byte1 = packet.getData();
String result = new String(byte1);
return result.substring(0, packetLength);
4
  • 3
    If the extra bites are all empty/whitespace, trim() should do it. Commented Apr 23, 2013 at 2:31
  • Something's fishy here. How do you, as a client, know when you've received the entire string? That is - what way do you have of knowing that you've gotten all of the character data? Commented Apr 23, 2013 at 2:32
  • This is a part of unit test code, so I know exactly the string I sent. Commented Apr 23, 2013 at 2:34
  • @Thomas: It works. Please make an answer so that I accept it. Commented Apr 23, 2013 at 2:36

2 Answers 2

1

maybe you should try to check the length of the data received AFTER receiving it:

http://docs.oracle.com/javase/1.5.0/docs/api/java/net/DatagramPacket.html#getLength%28%29

this should be 4 (after the call to socket.receive())

Sign up to request clarification or add additional context in comments.

1 Comment

the "setLength()" method is for sending, not for receiving.
0

If the extra bites are all empty/whitespace, trim() should do it.

1 Comment

this is actually incorrect if the message in the datagram is SUPPOSED to contain leading and/or trailing whitespace. please consider my answer below (with a link to the documentation)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.