2

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?

2
  • What exactly are you trying to accomplish? Commented Apr 27, 2011 at 4:13
  • I'm storing Strings on disk in a fixed size area (128 bytes), then trying to read the string back from disk. Commented Apr 27, 2011 at 4:14

2 Answers 2

3

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.

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.