Date: 2010dec10
Update: 2025oct13
Language: Java
Keywords: growable byte array
Q. Java: Is there something like the StringBuilder class for bytes?
(ie growable array)
A. Use ByteArrayOutputStream. Despite the name it has nothing to do
with output or streams. Its just a growable byte array.
ByteArrayOutputStream myBytes = new ByteArrayOutputStream();
my_bytes.write(other_bytes); // Append
my_bytes.size(); // How many?
my_bytes.reset(); // clear, make empty
One problem with this class is that write() can throw an IOException
so try-ing and catch-ing is a pain. And it should be called append()
So here is our wrapper class as shown in a full example:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
class Demo {
static class MyByteArray extends ByteArrayOutputStream {
void append(byte[] more) {
try {
write(more);
} catch (IOException ex) {
System.err.println("Could not write because " + ex.getMessage());
}
}
void append(final byte in) {
write(in);
}
void clear() {
reset();
}
}
public static final void main(String[] args) {
//
// Create and append some data
//
MyByteArray ba = new MyByteArray();
ba.append((byte)0xaa);
ba.append((byte)0xbb);
ba.append((byte)0xcc);
//
// Output
//
var array = ba.toByteArray();
for (int i = 0; i < array.length; i++) {
System.out.println("byte=" + String.format("0x%02x", array[i]));
}
}
}
Output:
byte=0xaa
byte=0xbb
byte=0xcc