samples/delegatingwriterfinal/src-api2.0/api/SimpleBuffer.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:53:07 +0200
changeset 67 b029a28df444
child 196 79eff053c4ec
permissions -rw-r--r--
As the purpose of buffer is to "buffer", let's modify our example to delegate to appendable methods directly only if the appendable is too big
jtulach@67
     1
package api;
jtulach@67
     2
jtulach@67
     3
import java.io.IOException;
jtulach@67
     4
jtulach@67
     5
/**
jtulach@67
     6
 *
jtulach@67
     7
 * @author Jaroslav Tulach
jtulach@67
     8
 */
jtulach@67
     9
final class SimpleBuffer implements Writer.ImplSeq {
jtulach@67
    10
    private final Writer out;
jtulach@67
    11
    private final StringBuffer sb = new StringBuffer();
jtulach@67
    12
    
jtulach@67
    13
    public SimpleBuffer(Writer out) {
jtulach@67
    14
        this.out = out;
jtulach@67
    15
    }
jtulach@67
    16
jtulach@67
    17
    public void close() throws IOException {
jtulach@67
    18
        flush();
jtulach@67
    19
        out.close();
jtulach@67
    20
    }
jtulach@67
    21
jtulach@67
    22
    public void flush() throws IOException {
jtulach@67
    23
        if (sb.length() > 0) {
jtulach@67
    24
            out.write(sb.toString());
jtulach@67
    25
            sb.setLength(0);
jtulach@67
    26
            out.flush();
jtulach@67
    27
        }
jtulach@67
    28
    }
jtulach@67
    29
jtulach@67
    30
    public void write(CharSequence seq) throws IOException {
jtulach@67
    31
        if (seq.length() < 1024) {
jtulach@67
    32
            sb.append(seq);
jtulach@67
    33
        } else {
jtulach@67
    34
            flush();
jtulach@67
    35
            out.append(seq);
jtulach@67
    36
        }
jtulach@67
    37
    }
jtulach@67
    38
jtulach@67
    39
}