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.

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
Steve
  • 4,457
  • 12
  • 48
  • 89
  • 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 Oct 21 '14 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? – ControlAltDel Oct 21 '14 at 14:29
  • @Joe Oh, there it is, I couldn't find my own stupid answer; thanks. – Dave Newton Oct 21 '14 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 Oct 21 '14 at 15:16

1 Answers1

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")))))
Fabian Barney
  • 14,219
  • 5
  • 40
  • 60