Reputation: 4640
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
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
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
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
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