/Users/lyon/j4p/src/classUtils/pack/util/TieOutputStream.java

1    package classUtils.pack.util; 
2     
3    import java.io.OutputStream; 
4    import java.io.PrintStream; 
5    import java.io.IOException; 
6     
7    /** 
8     * An OutputStream which ties output to two underlying streams. Any character written to the stream 
9     * is replicated on both. 
10    * 
11    * @author C. Sadun 
12    * @version 1.2 
13    */ 
14   public class TieOutputStream extends OutputStream 
15   { 
16      private OutputStream os1; 
17      private OutputStream os2; 
18    
19      /** 
20       * Build a OutputStream that ties togheter the two given streams. 
21       * Every output operation on the OutputStream will be replicated on both. 
22       * @param os1 the first stream 
23       * @param os2 the second stream 
24       */ 
25      public TieOutputStream(OutputStream os1, OutputStream os2) 
26      { this.os1=os1; 
27        this.os2=os2; 
28      } 
29    
30      /** 
31       * Write a byte to the stream, and thus to the two underlying streams. 
32       * 
33       * @param b the byte to write 
34       * @exception IOException if something fails during writing 
35       */ 
36      public void write(int b) throws IOException 
37      { 
38       os1.write(b); 
39       doCheckError(os1); 
40       os2.write(b); 
41       doCheckError(os2); 
42      } 
43    
44      /** 
45       * Close both underlying streams 
46       * 
47       * @param b the byte to write 
48       * @exception IOException if something fails during closing 
49       */ 
50      public void close() throws IOException { 
51       os1.close(); 
52       doCheckError(os1); 
53       os2.close(); 
54       doCheckError(os2); 
55      } 
56    
57      /** 
58       * Flush both underlying streams 
59       * 
60       * @param b the byte to write 
61       * @exception IOException if something fails during flushing 
62       */ 
63      public void flush() throws IOException { 
64       os1.flush(); 
65       doCheckError(os1); 
66       os2.flush(); 
67       doCheckError(os2); 
68      } 
69    
70      /** 
71       * Return the first of the two tied writers 
72       * @return the first of the two tied writers 
73       */ 
74      public OutputStream getFirstWriter() { return os1; } 
75    
76      /** 
77       * Return the second of the two tied writers 
78       * @return the second of the two tied writers 
79       */ 
80      public OutputStream getSecondWriter() { return os2; } 
81    
82      // If the writer's of PrintStream flavor, do an explicit 
83      // error check and raise an IOException in case of error 
84      private void doCheckError(OutputStream w) throws IOException { 
85       if (w instanceof PrintStream) 
86           if (((PrintStream)w).checkError()) 
87               throw new IOException("Operation on printwriter failed"); 
88      } 
89    
90    
91   } 
92