Issue
I have the following code:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int size = 4096;
byte[] bytes = new byte[size];
while (is.read(bytes, 0, size) != -1)
{
baos.write(bytes);
baos.flush();
}
When I do:
String s = baos.toString();
I get \u0000
-s appended to my string. So, if my character data is only X bytes out of Y, the Y-Z will get prefilled with \u0000
making it impossible to check for equals
. What am I doing wrong here? How should I be converting the bytes to a String
in this case?
Solution
You should only be writing as much data as you are reading in each time through the loop:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int size;
byte[] bytes = new byte[4096];
while (size = is.read(bytes, 0, bytes.length) != -1)
{
baos.write(bytes, 0, size);
}
baos.flush();
String s = baos.toString();
You might consider specifying a specific character set for converting the bytes to a String
. The no-arg toString()
method uses the platform default encoding.
Answered By - Ted Hopp
Answer Checked By - Senaida (JavaFixing Volunteer)