1

Is it possible to concatenate two OutputStreams (of the same type, stored as OutputStreams) without converting either to a string? If so, how?

3
  • 6
    Do you mean InputStreams? I can't imagine what concatenating OutputStreams would mean. Commented Feb 1, 2012 at 22:51
  • 1
    Please elaborate. How do you plan to do this? Are these files? Can you implement your own output stream object? Commented Feb 1, 2012 at 22:51
  • I am using a third-party library to retrieve data in the form of an OutputStream, and I wondered if there was a way to combine results into one stream.
    – winchella
    Commented Feb 2, 2012 at 16:35

2 Answers 2

1

So, If you have OutputStream A, and OutputStream B, and you want to concatenate them so that you end up with the stuff from A, followed by the stuff from B, you could convert B into an InputStream (a task that has likely been explained over 9000 times in this forum), and then Read data from this new InputStream, and write it to A. There: A generic answer for a generic question. Good luck!

2
  • That makes sense. Is there much benefit to this method over converting everything to a string and back? I might be dealing with a large number of streams.
    – winchella
    Commented Feb 2, 2012 at 16:41
  • 2
    Not really. This method, like any, is pretty inefficient (O(x) for those keeping score). If you are dealing with a large number of streams, you may wish to rethink your design, as it should save you a pretty good amount of time. Good Luck!
    – Cody S
    Commented Feb 3, 2012 at 18:37
0

A short example:

private void test(Document xmlDoc) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    String s1 = "header";
    outputStream.write(s1.getBytes());
    ByteArrayOutputStream bodySubTree = (ByteArrayOutputStream) xmlToOutStream(xmlDoc);
    outputStream.write(bodySubTree.toByteArray());
    String s2 = "footer";
    outputStream.write(s2.getBytes());
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.