| 1 | package org.amicofragile.io; |
| 2 | |
| 3 | import java.io.IOException; |
| 4 | import java.io.OutputStream; |
| 5 | |
| 6 | /** |
| 7 | * {@link OutputStream} which delegates to multiple {@link OutputStream}s. |
| 8 | * @author Pietro Martinelli |
| 9 | */ |
| 10 | public class TeeOutputStream extends OutputStream { |
| 11 | /** |
| 12 | * First stream to delegate to. |
| 13 | */ |
| 14 | private final OutputStream mainStream; |
| 15 | /** |
| 16 | * Other streams to delegate to. |
| 17 | */ |
| 18 | private final OutputStream[] streams; |
| 19 | /** |
| 20 | * @param mainStream First nested stream |
| 21 | * @param streams Optional nested streams |
| 22 | */ |
| 23 | public TeeOutputStream(final OutputStream mainStream, final OutputStream ... streams) { |
| 24 | this.mainStream = mainStream; |
| 25 | this.streams = streams; |
| 26 | } |
| 27 | /** |
| 28 | * @see OutputStream#write(int) |
| 29 | * @param b byte to write |
| 30 | * @throws IOException when nested stream throws |
| 31 | */ |
| 32 | @Override |
| 33 | public final void write(final int b) throws IOException { |
| 34 | this.mainStream.write(b); |
| 35 | for (OutputStream outputStream : streams) { |
| 36 | outputStream.write(b); |
| 37 | } |
| 38 | } |
| 39 | /** |
| 40 | * @see OutputStream#flush() |
| 41 | * @throws IOException when nested stream throws |
| 42 | */ |
| 43 | @Override |
| 44 | public final void flush() throws IOException { |
| 45 | this.mainStream.flush(); |
| 46 | for (OutputStream stream : streams) { |
| 47 | stream.flush(); |
| 48 | } |
| 49 | } |
| 50 | /** |
| 51 | * @see OutputStream#close() |
| 52 | * @throws IOException when nested stream throws |
| 53 | */ |
| 54 | @Override |
| 55 | public final void close() throws IOException { |
| 56 | this.mainStream.close(); |
| 57 | for (OutputStream stream : streams) { |
| 58 | stream.close(); |
| 59 | } |
| 60 | } |
| 61 | } |