java : Returning stream or resulting bytes

I have need to return the byte array for the ByteArrayOutputStream from the called method. I see two ways to achieve the same thing: firstly to return ByteArrayOutputStream & use toByteArray() method, and secondly use baos.toByteArray() and return the byte array.

Which one should I use?

To illustrate by example:

Method 1

void parentMethod(){
        bytes [] result = process();
    }
    void byte[] process(){
        ByteArrayOutputStream baos;
        .....
        .....
        .....
        baos.toByteArray();
    }

Method 2

void parentMethod(){
        ByteArrayOutputStream baos = process();     
    }
    void ByteArrayOutputStream process(){
        ByteArrayOutputStream baos;
        .....
        .....
        .....
        return baos;
    }
Jon Skeet
people
quotationmark

There's another alternative: return an InputStream. The idea is presumably that you're returning the data resulting from the operation. As such, returning an output stream seems very odd to me. To return data, you'd normally either return the raw byte[], or an InputStream wrapping it - the latter is more flexible in that it could be reading from a file or something similar, but does require the caller to close the stream afterwards.

It partly depends on what callers want to do with the data, too - there are some operations which are easier to perform if you've already got a stream; there are others which are easier with a byte array. I'd let that influence the decision quite a lot.

If you do want to return a stream, that's easy:

return new ByteArrayInputStream(baos.toByteArray());

So to summarize:

  • Don't return ByteArrayOutputStream. The use of that class in coming up with the data is an implementation detail, and it's not really the logical result of the operation.
  • Consider returning an InputStream if callers are likely to find that easier to use or if you may later want to read the data from a file (or network connection, or whatever); ByteArrayInputStream is suitable in the current implementation

people

See more on this question at Stackoverflow