Search code examples
javaioapache-commonsbytearrayoutputstream

Adding up ByteArrayOutputStreams


Im having a bunch of ByteArrayOutputstreams onto which pdf reports are written over different parts of a particular workflow. I use IText to accomplish this. Now, at the end I would like to group all these single ByteArrayOutputstreams into a bigger ByteArrayOutputstream so as to group all pdf reports together.

I looked at Apache Commons library but could not find anything of use.

1 way that i know of is to convert each of these ByteArrayOutputstreams into byte[] and then using System.arraycopy to copy them into a bigger byte[]. The problem with this is me having to declare the size of the result byte[] upfront which makes it non-ideal.

Is there any other way to copy/append to/concatenate ByteArrayOutputStreams taht i may have missed ?


Solution

  • You can use a List<Byte[]> for that. You can add your bytes on the go to the list.

    List<Byte[]> listOfAllBytes = new ArrayList<Byte[]>;
    ByteArrayOutputstreams byteArray = //...
    listOfAllBytes.add(byteArray.toByteArray);
    

    At the end, you can just get the full byte array back.