1 package com.quadcap.io; 2 3 40 41 import java.io.IOException ; 42 import java.io.Writer ; 43 44 import java.util.HashMap ; 45 import java.util.Iterator ; 46 47 51 public class TeeWriter extends Writer { 52 class WriterBinding { 53 Writer w; 54 boolean passFlush = true; 55 boolean passClose = true; 56 boolean autoFlush = false; 57 boolean enabled = true; 58 WriterBinding(Writer w) { this.w = w; } 59 } 60 61 HashMap writers = new HashMap (); 62 63 66 public TeeWriter() {} 67 68 public TeeWriter(Writer w) { addWriter("", w); } 69 70 73 public void write(char[] buf, int off, int len) throws IOException { 74 Iterator iter = writers.values().iterator(); 75 while (iter.hasNext()) { 76 WriterBinding wb = (WriterBinding)iter.next(); 77 if (wb.enabled) { 78 wb.w.write(buf, off, len); 79 if (wb.autoFlush) { 80 wb.w.flush(); 81 } 82 } 83 } 84 } 85 86 89 public void flush() throws IOException { 90 Iterator iter = writers.values().iterator(); 91 while (iter.hasNext()) { 92 WriterBinding wb = (WriterBinding)iter.next(); 93 if (wb.enabled && wb.passFlush) wb.w.flush(); 94 } 95 } 96 97 100 public void close() throws IOException { 101 Iterator iter = writers.values().iterator(); 102 while (iter.hasNext()) { 103 WriterBinding wb = (WriterBinding)iter.next(); 104 if (wb.enabled && wb.passClose) wb.w.close(); 105 } 106 } 107 108 111 public void addWriter(String name, Writer w) { 112 WriterBinding wb = new WriterBinding(w); 113 writers.put(name, wb); 114 } 115 116 119 public void removeWriter(String name) { 120 writers.remove(name); 121 } 122 123 public void setPassClose(String w, boolean b) throws IOException { 124 getBinding(w).passClose = b; 125 } 126 127 public void setPassFlush(String w, boolean b) throws IOException { 128 getBinding(w).passFlush = b; 129 } 130 131 public void setAutoFlush(String w, boolean b) throws IOException { 132 getBinding(w).autoFlush = b; 133 } 134 135 public void setEnabled(String w, boolean b) throws IOException { 136 getBinding(w).enabled = b; 137 } 138 139 final private WriterBinding getBinding(String w) throws IOException { 140 WriterBinding wb = (WriterBinding)writers.get(w); 141 if (wb == null) { 142 throw new IOException ("No writer: " + w); 143 } 144 return wb; 145 } 146 147 } 148 | Popular Tags |