1
package org.crosswire.io;
3
import java.io.IOException;
5
import java.util.Vector;
7
import org.crosswire.util.Level;
8
import org.crosswire.util.Logger;
11
* TeeWriter allows you to have one stream act as a proxy
12
* to a number of other streams, so that output to one goes to all
16
public class TeeWriter extends Writer
19
* Add the specified Writer to the list of streams.
21
* @return "this". So we can do <pre>tee.add(a).add(b).add(c);</pre>
23
public TeeWriter add(Writer out)
25
if (!list.contains(out))
34
* Remove the specified Writer from the list of streams
35
* used in all outputs.
36
* @param out The Stream to be removed
38
public boolean remove(Writer out)
40
return list.removeElement(out);
44
* Override write to ask the listed Streams.
45
* @param b The byte to be written, as normal.
47
public void write(char[] cbuf, int off, int len) throws IOException
49
for (int i=0; i<list.size(); i++)
51
Writer out = (Writer) list.elementAt(i);
52
out.write(cbuf, off, len);
57
* Override write to ask the listed Streams.
58
* @param b The byte to be written, as normal.
60
public void write(int b) throws IOException
62
for (int i=0; i<list.size(); i++)
64
Writer out = (Writer) list.elementAt(i);
70
* Override flush to flush the listed Streams.
72
public void flush() throws IOException
74
for (int i=0; i<list.size(); i++)
76
Writer out = (Writer) list.elementAt(i);
82
* If someone closes the TeeWriter then we go round
83
* and close all the Streams on the stack.
85
public void close() throws IOException
87
// Close each Writer catching and noting IOExceptions
88
// Then rethrow at end if any failed.
89
boolean failed = false;
91
for (int i=0; i<list.size(); i++)
95
Writer out = (Writer) list.elementAt(i);
100
log.log(Level.INFO, "Error in closing loop", ex);
105
list.removeAllElements();
107
if (failed) throw new IOException();
111
* @return The number of items on the stack
119
* Primarily for debugging. Reports on th state of the Stream.
120
* @return A String containing the report.
122
public String toString()
125
String NEWLINE = System.getProperty("line.separator", "\r\n");
127
retcode += "There are " + list.size() + " output(s)" + NEWLINE;
129
for (int i=list.size()-1; i>=0; i--)
131
Writer out = (Writer) list.elementAt(i);
132
retcode += "Stream" + i + ": " + out.toString() + NEWLINE;
138
private Vector list = new Vector();
140
/** The log stream */
141
protected static Logger log = Logger.getLogger(TeeWriter.class);