1 7 8 package java.io; 9 10 23 public 24 class CharArrayWriter extends Writer { 25 28 protected char buf[]; 29 30 33 protected int count; 34 35 38 public CharArrayWriter() { 39 this(32); 40 } 41 42 48 public CharArrayWriter(int initialSize) { 49 if (initialSize < 0) { 50 throw new IllegalArgumentException ("Negative initial size: " 51 + initialSize); 52 } 53 buf = new char[initialSize]; 54 } 55 56 59 public void write(int c) { 60 synchronized (lock) { 61 int newcount = count + 1; 62 if (newcount > buf.length) { 63 char newbuf[] = new char[Math.max(buf.length << 1, newcount)]; 64 System.arraycopy(buf, 0, newbuf, 0, count); 65 buf = newbuf; 66 } 67 buf[count] = (char)c; 68 count = newcount; 69 } 70 } 71 72 78 public void write(char c[], int off, int len) { 79 if ((off < 0) || (off > c.length) || (len < 0) || 80 ((off + len) > c.length) || ((off + len) < 0)) { 81 throw new IndexOutOfBoundsException (); 82 } else if (len == 0) { 83 return; 84 } 85 synchronized (lock) { 86 int newcount = count + len; 87 if (newcount > buf.length) { 88 char newbuf[] = new char[Math.max(buf.length << 1, newcount)]; 89 System.arraycopy(buf, 0, newbuf, 0, count); 90 buf = newbuf; 91 } 92 System.arraycopy(c, off, buf, count, len); 93 count = newcount; 94 } 95 } 96 97 103 public void write(String str, int off, int len) { 104 synchronized (lock) { 105 int newcount = count + len; 106 if (newcount > buf.length) { 107 char newbuf[] = new char[Math.max(buf.length << 1, newcount)]; 108 System.arraycopy(buf, 0, newbuf, 0, count); 109 buf = newbuf; 110 } 111 str.getChars(off, off + len, buf, count); 112 count = newcount; 113 } 114 } 115 116 122 public void writeTo(Writer out) throws IOException { 123 synchronized (lock) { 124 out.write(buf, 0, count); 125 } 126 } 127 128 152 public CharArrayWriter append(CharSequence csq) { 153 String s = (csq == null ? "null" : csq.toString()); 154 write(s, 0, s.length()); 155 return this; 156 } 157 158 190 public CharArrayWriter append(CharSequence csq, int start, int end) { 191 String s = (csq == null ? "null" : csq).subSequence(start, end).toString(); 192 write(s, 0, s.length()); 193 return this; 194 } 195 196 212 public CharArrayWriter append(char c) { 213 write(c); 214 return this; 215 } 216 217 221 public void reset() { 222 count = 0; 223 } 224 225 230 public char toCharArray()[] { 231 synchronized (lock) { 232 char newbuf[] = new char[count]; 233 System.arraycopy(buf, 0, newbuf, 0, count); 234 return newbuf; 235 } 236 } 237 238 243 public int size() { 244 return count; 245 } 246 247 251 public String toString() { 252 synchronized (lock) { 253 return new String (buf, 0, count); 254 } 255 } 256 257 260 public void flush() { } 261 262 267 public void close() { } 268 269 } 270 | Popular Tags |