KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > util > CharSpool


1 package hudson.util;
2
3 import java.io.IOException JavaDoc;
4 import java.io.Writer JavaDoc;
5 import java.util.LinkedList JavaDoc;
6 import java.util.List JavaDoc;
7
8 /**
9  * {@link Writer} that spools the output and writes to another {@link Writer} later.
10  *
11  * @author Kohsuke Kawaguchi
12  */

13 public final class CharSpool extends Writer JavaDoc {
14     private List JavaDoc<char[]> buf;
15
16     private char[] last = new char[1024];
17     private int pos;
18
19     public void write(char cbuf[], int off, int len) {
20         while(len>0) {
21             int sz = Math.min(last.length-pos,len);
22             System.arraycopy(cbuf,off,last,pos,sz);
23             len -= sz;
24             off += sz;
25             pos += sz;
26             renew();
27         }
28     }
29
30     private void renew() {
31         if(pos<last.length)
32             return;
33
34         if(buf==null)
35             buf = new LinkedList JavaDoc<char[]>();
36         buf.add(last);
37         last = new char[1024];
38         pos = 0;
39     }
40
41     public void write(int c) {
42         renew();
43         last[pos++] = (char)c;
44     }
45
46     public void flush() {
47         // noop
48
}
49
50     public void close() {
51         // noop
52
}
53
54     public void writeTo(Writer JavaDoc w) throws IOException JavaDoc {
55         if(buf!=null) {
56             for (char[] cb : buf) {
57                 w.write(cb);
58             }
59         }
60         w.write(last,0,pos);
61     }
62 }
63
Popular Tags