22

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
 }
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
bob
  • 1,941
  • 6
  • 26
  • 36

3 Answers3

28

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.

Soulman
  • 2,910
  • 24
  • 21
18

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.

Ian Dallas
  • 12,451
  • 19
  • 58
  • 82
  • 2
    What encoding does your text use? Method above will work with ASCII but may fail on any multi-byte strings like UTF-8 or UTF-16 (you may read partial string from buffer and get only half of char definition at the end; also leaving invalid beginning for next portion) – tomash Aug 11 '12 at 14:29
  • 6
    `String s = new String(buffer, 0, len, "UTF-8");` for other encodings than ASCII – Cԃաԃ Dec 04 '13 at 04:55
  • Did you check by any chance if this performs faster than `ByteArrayOutputStream`? I suppose it will. – Kashyap Oct 15 '15 at 17:15
  • @Kashyap has a good point, and it may also break the string in the middle of a code point. – Jonas Byström May 16 '16 at 13:10
-2

Something like below should do the trick for you.

byte[] buffer = new byte[3];
buffer[0] = 'a';
buffer[1] = 'b';
buffer[2] = 'c';
StringBuilder sb = new StringBuilder(new String(buffer,0,buffer.length-1));
System.out.println("buffer has:"+sb.toString()); //prints ab
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
CoolBeans
  • 20,654
  • 10
  • 86
  • 101