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 0
s 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?
-
What exactly are you trying to accomplish?Stefan Kendall– Stefan Kendall04/27/2011 04:13:20Commented 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.meteoritepanama– meteoritepanama04/27/2011 04:14:28Commented Apr 27, 2011 at 4:14
Add a comment
|
2 Answers
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
.
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.