samples/delegatingwriterfinal/src-api2.0/api/SimpleBuffer.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 10:04:53 +0200
changeset 210 acf2c31e22d4
parent 209 1c999569643b
permissions -rw-r--r--
Merge: Geertjan's changes to the end of the chapter
     1 package api;
     2 
     3 import java.io.IOException;
     4 
     5 /**
     6  *
     7  * @author Jaroslav Tulach
     8  */
     9 final class SimpleBuffer implements Writer.ImplSeq {
    10     private final Writer out;
    11     private final StringBuffer sb = new StringBuffer();
    12     
    13     public SimpleBuffer(Writer out) {
    14         this.out = out;
    15     }
    16 
    17     public void close() throws IOException {
    18         flush();
    19         out.close();
    20     }
    21 
    22     public void flush() throws IOException {
    23         if (sb.length() > 0) {
    24             out.write(sb.toString());
    25             sb.setLength(0);
    26             out.flush();
    27         }
    28     }
    29 
    30     public void write(CharSequence seq) throws IOException {
    31         if (shouldBufferAsTheSequenceIsNotTooBig(seq)) {
    32             sb.append(seq);
    33         } else {
    34             flush();
    35             out.append(seq);
    36         }
    37     }
    38 
    39     /** At the end the purpose of BufferedWriter is to buffer writes, this
    40      * method is here to decide when it is OK to prefer buffering and when 
    41      * it is better to delegate directly into the underlaying stream.
    42      * 
    43      * @param csq the seqence to evaluate
    44      * @return true if buffering from super class should be used
    45      */
    46     private static boolean shouldBufferAsTheSequenceIsNotTooBig(CharSequence csq) {
    47         if (csq == null) {
    48             return false;
    49         }
    50         // as buffers are usually bigger than 1024, it makes sense to 
    51         // pay the penalty of converting the sequence to string, but buffering
    52         // the write
    53         if (csq.length() < 1024) {
    54             return true;
    55         } else {
    56             // otherwise, just directly write down the char sequence
    57             return false;
    58         }
    59     }
    60     
    61 }