How do you merge two input streams in Java?

pupeno picture pupeno · Apr 17, 2009 · Viewed 31.6k times · Source

Having two InputStreams in Java, is there a way to merge them so you end with one InputStream that gives you the output of both streams? How?

Answer

Tom Hawtin - tackline picture Tom Hawtin - tackline · Apr 17, 2009

As commented, it's not clear what you mean by merge.

Taking available input "randomly" from either is complicated by InputStream.available not necessarily giving you a useful answer and blocking behaviour of streams. You would need two threads to be reading from the streams and then passing back data through, say, java.io.Piped(In|Out)putStream (although those classes have issues). Alternatively for some types of stream it may be possible to use a different interface, for instance java.nio non-blocking channels.

If you want the full contents of the first input stream followed by the second: new java.io.SequenceInputStream(s1, s2).