return multiple byte arrays using ByteArrayOutputStream

579 Views Asked by At

I am struggling to return multiple byte arrays using ByteArrayOutputStream. I have multiple string values that need to be converted to separate byte arrays and then return each one of them. My issue is that toByteArray() method does not work on ByteArrayOutputStream[], compiler shows following error "cannot invoke toByteArray() on the array type ByteArrayOutputStream[]". Here is the code:

int Count = getListsize.size(); <--- List has two elements of type String
ByteArrayOutputStream[] baos = new ByteArrayOutputStream[Count];

   for (int i = 0; i < Count; i++) {
        baos[i].write("string".getBytes());
                    
   }
    return baos.toByteArray();   <--- Doesn't work with the ByteArrayOutputStream[]
1

There are 1 best solutions below

1
Louis Wasserman On

You have to call toByteArray() on each individual ByteArrayOutputStream in the array. You can create your own byte[][] to store that in. That said, of course, the code you've shown us has no reason to use ByteArrayOutputStream, since it's just using it to copy the result of "string".getBytes().