DatagramPacket to string


Trying to convert a received DatagramPacket to string, but I have a small problem. Not sure what's the best way to go about it.

The data I'll be receiving is mostly of unknown length, hence I have some buffer[1024] set on my receiving side. The problem is, suppose I sent string "abc" and the do the following on my receiver side...

buffer = new byte[1024];
packet = new DatagramPacket(buffer, buffer.length);
buffer = packet.getData();
System.out.println("Received: "+new String(buffer));

I get the following output: abc[][][][]][][][]..... all the way to the buffer length. I'm guessing all the junk/null at the end should've been ignored, so I must be doing something wrong." I know the buffer.length is the problem because if I change it to 3 (for this example), my out comes out just fine.


new String(buffer, 0, packet.getLength())