meteoritepanama
meteoritepanama

Reputation: 6242

Java: Converting fixed size byte array to a variable length String

Is there a way to convert a fixed size byte array to a String without iterating over the byte array to find where the String ends? The problem I'm having is that not all of the bytes in the byte array are characters. I'm padding the end of the array with 0. If I use new String(byte[]), it interprets the 0s as part of the string. Is there a certain character I can pad the byte[] with and not have it interpret it as part of the String?

Upvotes: 2

Views: 2048

Answers (2)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

There's a String constructor that takes a byte[], a begin offset, and a length as arguments -- just use that to tell the String which bytes to include.

Upvotes: 2

C. K. Young
C. K. Young

Reputation: 223003

No, since all byte values are valid characters in a string. You must keep track of the count of valid bytes, and use the byte[], int, int version of the constructor.

If you don't want to keep track of the count manually (perhaps because you are building the byte array piecemeal), consider using a ByteArrayOutputStream.

Upvotes: 3

Related Questions