5

I have an OutputStream, and I'd like to (on a conceptual level) broadcast it to multiple files. So for instance, if a byte shows up in the stream, I want that to get written to files A, B, and C.

How can I accomplish this using only one stream? Preferably with a pure Java solution.

4
  • 4
    It would be pretty trivial to write an implementation of OutputStream which proxied a list of OutputStreams and forwarded any calls to each one in turn.
    – BarrySW19
    Commented Oct 21, 2014 at 14:29
  • I am confused: You write bytes to an OutputStream, not read them. So do you actually have an InputStream? If not, where are your bytes coming from? Commented Oct 21, 2014 at 14:29
  • @Joe Oh, there it is, I couldn't find my own stupid answer; thanks. Commented Oct 21, 2014 at 14:50
  • Oh snap, you guys are right. I looked all over but didn't see that one. What's the process now, do I delete this question since it's duplicate?
    – Steve
    Commented Oct 21, 2014 at 15:16

1 Answer 1

6

You can use Apache Commons IO TeeOutputStream for this purpose. This OutputStream proxies all bytes written to it to two underlying OutputStreams. You can use multiple TeeOutputStreams in a chain when you want to write to more than two OutputStreams at once.

OutputStream out = new TeeOutputStream(
  new FileOutputStream(new File("A")), 
  new TeeOutputStream(
      new FileOutputStream(new File("B")), 
      new FileOutputStream(new File("C"))
  )
);
2
  • flawless answer Fabian! Will surely check out TeeOutputStream.
    – Gaurav
    Commented Aug 2, 2019 at 18:49
  • 1
    Why isn't something like that in the standard library?
    – matj1
    Commented May 24, 2022 at 8:14

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