Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append part of Java byte array to StringBuilder

Tags:

How do I append a portion of byte array to a StringBuilder object under Java? I have a segment of a function that reads from an InputStream into a byte array. I then want to append whatever I read into a StringBuilder object:

byte[] buffer = new byte[4096];
InputStream is;
//
//some setup code
//
while (is.available() > 0)
{
   int len = is.read(buffer);
   //I want to append buffer[0] to buffer[len] into StringBuilder at this point
 }
like image 403
bob Avatar asked Feb 09 '11 22:02

bob


People also ask

Can we append character in StringBuilder?

append(char c) method appends the string representation of the char argument to this sequence. The argument is appended to the contents of this sequence. The length of this sequence increases by 1.

What is append in StringBuilder append?

append(char[] str) Appends the string representation of the char array argument to this sequence. StringBuilder. append(char[] str, int offset, int len) Appends the string representation of a subarray of the char array argument to this sequence.

Can we append final StringBuilder?

sb. append doesn't assign a new value to sb , only mutates the state of the instance already referred by sb . Therefore it is allowed, even for final variables.


2 Answers

You should not use a StringBuilder for this, since this can cause encoding errors for variable-width encodings. You can use a java.io.ByteArrayOutputStream instead, and convert it to a string when all data has been read:

byte[] buffer = new byte[4096]; ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream is; // //some setup code // while (is.available() > 0) {    int len = is.read(buffer);    out.write(buffer, 0, len); } String result = out.toString("UTF-8"); // for instance 

If the encoding is known not to contain multi-byte sequences (you are working with ASCII data, for instance), then using a StringBuilder will work.

like image 93
Soulman Avatar answered Oct 07 '22 18:10

Soulman


You could just create a String out of your buffer:

String s = new String(buffer, 0, len);

Then if you need to you can just append it to a StringBuilder.

like image 22
Ian Dallas Avatar answered Oct 07 '22 18:10

Ian Dallas