Zai Zai - 10 months ago 51
Java Question

How can erase the contents of an array in Java with safety?

I'm trying to receive data from a client and then log it onto the console.
Here is how i do this:

private final int MAX_PACKET_SIZE = 1024;
private byte[] data = new byte[MAX_PACKET_SIZE];

private void receive() {
new Thread(() -> {
while (running) {
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
sPort = packet.getPort();
ip = packet.getAddress();
address = ip.toString();
} catch (Exception e) {
String messageToPrint = new String(packet.getData());
System.out.println(messageToPrint.trim() + " " + address + " | " + sPort);

When it comes to printing my
it actually repeats the last one, and reprinting it with a newer one.

I've figured out what is the problem though.

If i put allocation of the array
inside the
loop, everything works fine and i don't get the previous message again, just current one.

I don't really want to do this, because allocation inside loops not a good idea so i need somehow to clear my array before new data comes in.

The output without allocation inside the loop is:

Console: past message

Console: (imagine i typed hello) hellomessage

and so on.

Answer Source

Create the packet outside of the loop, and also retrieve size data from the packet. (Otherwise you'll print the entire array which could contain the trailing text of the last message received)

final DatagramPacket packet = new DatagramPacket(data, data.length);
while (running) {
    try {
    final String messageToPrint = new String(