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