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);
prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

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())

rmalchow
  • 2,689
  • 18
  • 31
0

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

Thomas
  • 5,074
  • 1
  • 16
  • 12
  • 1
    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) – rmalchow Apr 23 '13 at 03:13