1 9 package javolution.io; 10 11 import j2me.lang.CharSequence; 12 import j2me.lang.IllegalStateException; 13 import j2me.lang.UnsupportedOperationException; 14 15 import java.io.IOException ; 16 import java.io.Writer ; 17 import javolution.lang.Reusable; 18 import javolution.text.Appendable; 19 import javolution.text.Text; 20 21 28 public final class AppendableWriter extends Writer implements Reusable { 29 30 33 private Appendable _output; 34 35 41 public AppendableWriter() { 42 } 43 44 55 public AppendableWriter setOutput(Appendable output) { 56 if (_output != null) 57 throw new IllegalStateException ("Writer not closed or reset"); 58 _output = output; 59 return this; 60 } 61 62 68 public void write(char c) throws IOException { 69 if (_output == null) 70 throw new IOException ("Writer closed"); 71 _output.append(c); 72 } 73 74 81 public void write(int c) throws IOException { 82 if (_output == null) 83 throw new IOException ("Writer closed"); 84 _output.append((char) c); 85 } 86 87 95 public void write(char cbuf[], int off, int len) throws IOException { 96 if (_output == null) 97 throw new IOException ("Writer closed"); 98 _tmpBuffer = cbuf; 99 _output.append(_tmpBufferAsCharSequence, off, off + len); 100 _tmpBuffer = null; } 102 103 private char[] _tmpBuffer; 104 105 private final CharSequence _tmpBufferAsCharSequence = new CharSequence () { 106 public int length() { 107 return _tmpBuffer.length; 108 } 109 110 public char charAt(int index) { 111 return _tmpBuffer[index]; 112 } 113 114 public CharSequence subSequence(int start, int end) { 115 throw new UnsupportedOperationException (); 116 } 117 }; 118 119 127 public void write(String str, int off, int len) throws IOException { 128 if (_output == null) 129 throw new IOException ("Writer closed"); 130 Object obj = str; 131 if (obj instanceof CharSequence ) { 132 _output.append((CharSequence ) obj); 133 } else { 134 _output.append(Text.valueOf(str)); 135 } 136 } 137 138 144 public void write(CharSequence csq) throws IOException { 145 if (_output == null) 146 throw new IOException ("Writer closed"); 147 _output.append(csq); 148 } 149 150 155 public void flush() throws IOException { 156 } 158 159 164 public void close() throws IOException { 165 if (_output != null) { 166 reset(); 167 } 168 } 169 170 public void reset() { 172 _output = null; 173 _tmpBuffer = null; 174 } 175 } | Popular Tags |