Arturs Vancans
Arturs Vancans

Reputation: 4640

Read byte array up to a NUL character

I am receiving a packet with byte array via UDP in Java. I know the maximum possible byte size, but I don't know currently received size.

If I create a String instance from this byte array, then the string will have lots and lots of NUL characters (\u0000) after the useful payload.

How do I convert this byte array to String up to a point when the first NUL appears? (I do not expect to have NUL in my payload).

Upvotes: 0

Views: 1066

Answers (4)

pstanton
pstanton

Reputation: 36640

I had to solve this recently, here's my solution:

public String getString(byte[] sb) {
    // trim nulls from end
    int strLen = sb.length;
    for (; strLen > 0; strLen--)
        if (sb[strLen - 1] != '\u0000')
            break;

    return new String(sb, 0, strLen, "UTF8");
}

Upvotes: 1

bmargulies
bmargulies

Reputation: 100051

Don't create the String from the whole thing. Scan the byte array for the zero, and then call

new String(byteArray, 0, correctLength, "encoding")

Upvotes: 1

Alden
Alden

Reputation: 837

String has a split method that will break it into an array of strings based on where a regex appears. You could do

    s = s.split("\u0000")[0];

to split the string around NUL characters and take the first section.

Upvotes: 1

MahshidYassaei
MahshidYassaei

Reputation: 61

You might be able to use StringTokenizer to get the first part of the string until you see the first NULL. something like: result = (new stringTokenizer(packet, null)).nextToken()

Upvotes: 1

Related Questions