How can I remove bytes from a ByteArrayOutputStream?

Grammin picture Grammin · Jun 27, 2012 · Viewed 8.4k times · Source

So the first four bytes of my ByteArrayOutputStream contain the length of a header in my stream. I need to remove that header from the stream and go on with my business.

ByteArrayOutputStream oStream = new ByteArrayOutputStream();
/* populate ByteArrayOutputStream */

//grab first int
int headerLength = oStream.toByteArray()[4];

//remove headerLength
String newString = oStream.toString().substring(jsonLength, oStream.size());
oStream.write(newString.getBytes());

I don't think this is the proper way to go about this though, does anyone have any suggestions?

Answer

Stephen C picture Stephen C · Jun 27, 2012

The simple answer is to write the 4 bytes in the first place ... if you can achieve that.

Another answer would be to write a custom FilterOutputStream subclass that ignores the first 4 bytes written.

Yet another is to extract the bytes, and then use one of the Arrays.copy methods to create a new byte array containing the "slice" of the original that you require; e.g.

byte[] subarray = Arrays.copyOfRange(original, 4, original.length - 4);

Or if your application can cope with an "undefined" area at the end of the byte array, you can do something like this:

System.arraycopy(array, 4, array.length - 4, array, 0);  // YMMV - check javadoc

Finally, depending on what you are using the byte array for, there's a good chance you can ignore the first 4 bytes without removing them. For instance, you can do this when writing bytes to a stream, when creating a string from bytes, when copying bytes to a ByteBuffer, and so on.